基础班 06 Stack & Queue
基础班 06 Stack & Queue
1
Stack & Queue
Two Different Data Structure
Stack: LIFO (Last in first out)
Queue: FIFO (First in first out)
2
Stack: LIFO
5
Queue: FIFO
1
5
Queue: FIFO
1 2
5
Queue: FIFO
1 2 3
5
Queue: FIFO
1 2 3 4
5
Queue: FIFO
1 2 3 4 5
5
Queue: FIFO
1 2 3 4 5
6
Queue: FIFO
2 3 4 5
6
Queue: FIFO
3 4 5
6
Queue: FIFO
4 5
6
Queue: FIFO
5
6
Queue: FIFO
6
Stack in Code
Java
Stack<String> stack = new Stack<>();
C++
stack<string> stack;
7
Basic Operations
Operation Input Output Time
Push Element Element O(1)
Pop void Element O(1)
Peek void Element O(1)
8
Stack Implementation
Define fields
Based on array
elements, size, capacity
Define functions
push, pop, peek
Source code:
http://developer.classpath.org/doc/java/util/Stack-
source.html
9 . 1
Stack Implementation- Fields
class Stack {
9 . 2
Stack Implementation- Push
class Stack {
9 . 3
Stack Implementation- Pop
class Stack {
9 . 4
Stack Implementation- Peek
class Stack {
9 . 5
When to use Stack?
Simulation of invoking a function
Recursion to Iteration (This is a special case of the
first)
DFS (Depth-first Search) (This is a special case of the
second)
Other
10 . 1
Stack in Operating System
Stack and Heap
Stack is faster
primitive variables, function calls
Heap can dynamically allocate space
reference variables.
10 . 2
Function call example
public class ExceptionHandling {
public static void main(String[] args)
{
fun();
}
public static void fun()
{
int a = 1;
int b = 2;
moreFun(a, b);
System.out.println("Method fun");
}
public static void moreFun(int x, int y)
{
int ans = x + y;
System.out.println(ans);
System.out.println("Method moreFun");
}
}
10 . 3
Queue in Code
Java
Queue<String> queue = new LinkedList<>();
C++
queue<string> queue;
11
Basic Operations
Operation Input Output Time
offer (add) Element boolean O(1)
poll (remove) void Element O(1)
Peek void Element O(1)
(element)
12 . 1
Basic Operations
Type of Throws Returns special
Operation exception value
Insert add(e) offer(e)
Remove remove() poll()
Examine element() peek()
12 . 2
Queue Implementation
Define fields
Based on array
elements, size, front_index, rear_index
Define functions
offer, poll, peek
poll, peek v.s. remove, element
poll, peek will return null when empty
LinkedList is used to implement features for Queue in
Java, so the implementation here is different
13 . 1
Queue Implementation -Fields
class Queue {
13 . 2
Queue Implementation - offer
class Queue {
13 . 3
Queue Implementation - poll
class Queue {
13 . 4
Queue Implementation - peek
class Queue {
13 . 5
When to use Queue?
BFS (Breadth-first Search)
Priority Queue (Heap)
Multi Task Queue (Design)
14
LinkedList Rule Them All
Head Tail
poll pollLast
push add
pollFirst removeLast
addFirst addAll
pop
offerFirst addLast
remove peekLast
offer
removeFirst getLast
offerLast
peek
element
getFirst
peekFirst java.util.LinkedList
15
Implement Queue using Stacks
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
16 . 1
Implement Queue using Stacks
Use two Stacks to implement a queue
Consider the basic operations of these two data structures
How to minimize the time complexity
16 . 2
Implement Queue using Stacks
class MyQueue {
16 . 3
Implement Queue using Stacks
class MyQueue {
16 . 4
Implement Queue using Stacks
class MyQueue {
16 . 5
Max Stack
Design a stack that supports push, pop, top, and retrieving the
maximum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMax() -- Retrieve the maximum element in the stack.
17 . 1
Max Stack
One stack cannot tell the max in O(1)
Need another stack to store the max
time <=> space
17 . 2
Max Stack
class MaxStack {
Stack<Integer> elements;
Stack<Integer> maxElements;
17 . 3
Max Stack
class MaxStack {
17 . 4
Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and
']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are
all valid but "(]" and "([)]" are not.
18 . 1
Valid Parentheses
We need to use the stack to store the information:
which left parentheses has not been matched yet
Stack can help store every unused parentheses, no
matter when the parentheses appears
18 . 2
Valid Parentheses
public boolean isValid(String s) {
Stack<Character> pair = new Stack<>();
int n = s.length();
if (n == 0) return true;
for (int i = 0; i < n; i ++) {
if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
pair.push(s.charAt(i));
} else if (s.charAt(i) == ')') {
if (pair.isEmpty() || pair.pop() != '(') return false;
} else if (s.charAt(i) == ']') {
if (pair.isEmpty() || pair.pop() != '[') return false;
} else if(s.charAt(i) == '}') {
if (pair.isEmpty() || pair.pop() != '{') return false;
}
}
return pair.isEmpty();
}
18 . 3
Decode String
Given an encoded string, return it's decoded string.
The encoding rule is: k[encoded_string], where the
encoded_string inside the square brackets is being repeated
exactly k times. Note that k is guaranteed to be a positive
integer.
You may assume that the input string is always valid; No extra
white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not
contain any digits and that digits are only for those repeat
numbers, k. For example, there won't be input like 3a or 2[4].
19 . 1
Decode String
Examples:
s="3[a]2[bc]", return "aaabcbc".
s="3[a2[c]]", return "accaccacc".
s="2[abc]3[cd]ef", return "abcabccdcdcdef".
19 . 2
Decode String
If it's number, update the number for the repeating
times.
If it's '[', store the previous string and try to get the
new string that needs to be repeated.
If it's ']', the current string is finished,
the previous string + repeating_times *
current_string
If it's other characters, update the current string.
19 . 3
public String decodeString(String s) {
int index = 0;
Stack<Integer> countStack = new Stack<>();
Stack<String> strStack = new Stack<>();
StringBuilder res = new StringBuilder();
while (index < s.length()) {
char c = s.charAt(index);
if (Character.isDigit(c)) {
int count = 0;
while (index < s.length() && Character.isDigit(s.charAt(index))) {
count = count * 10 + (s.charAt(index++) - '0');
}
countStack.push(count);
} else if (c == '[') {
strStack.push(res.toString());
res = new StringBuilder();
index++;
} else if (c == ']') {
StringBuilder temp = new StringBuilder(strStack.pop());
int count = countStack.pop();
for (int i = 0; i < count; i++) {
temp.append(res);
}
res = temp;
index++;
} else {
res.append(c);
index++;
}
}
return res.toString();
}
19 . 4
Homework (optional)
Simplify Path
Evaluate Reverse Polish Notation
Implementing Stack using Queues
Flatten Nested List Iterator
20