0% found this document useful (0 votes)
13 views63 pages

基础班 06 Stack & Queue

Uploaded by

susij
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views63 pages

基础班 06 Stack & Queue

Uploaded by

susij
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Stack & Queue

1
Stack & Queue
Two Different Data Structure
Stack: LIFO (Last in first out)
Queue: FIFO (First in first out)

2
Stack: LIFO

LIFO: Last In First Out

Copyright © 直通硅⾕ Tower of Hanoi


http://www.zhitongguigu.com 3
Stack: LIFO
1

LIFO: Last In First Out

Copyright © 直通硅⾕ Tower of Hanoi


http://www.zhitongguigu.com 3
Stack: LIFO
1 2

LIFO: Last In First Out

Copyright © 直通硅⾕ Tower of Hanoi


http://www.zhitongguigu.com 3
Stack: LIFO
1 2 3

LIFO: Last In First Out

Copyright © 直通硅⾕ Tower of Hanoi


http://www.zhitongguigu.com 3
Stack: LIFO
1 2 3 4

LIFO: Last In First Out

Copyright © 直通硅⾕ Tower of Hanoi


http://www.zhitongguigu.com 3
Stack: LIFO
1 2 3 4 5

LIFO: Last In First Out

Copyright © 直通硅⾕ Tower of Hanoi


http://www.zhitongguigu.com 3
Stack: LIFO
1 2 3 4 5

LIFO: Last In First Out

Copyright © 直通硅⾕ Tower of Hanoi


http://www.zhitongguigu.com 4
Stack: LIFO
1 2 3 4

LIFO: Last In First Out

Copyright © 直通硅⾕ Tower of Hanoi


http://www.zhitongguigu.com 4
Stack: LIFO
1 2 3

LIFO: Last In First Out

Copyright © 直通硅⾕ Tower of Hanoi


http://www.zhitongguigu.com 4
Stack: LIFO
1 2

LIFO: Last In First Out

Copyright © 直通硅⾕ Tower of Hanoi


http://www.zhitongguigu.com 4
Stack: LIFO
1

LIFO: Last In First Out

Copyright © 直通硅⾕ Tower of Hanoi


http://www.zhitongguigu.com 4
Stack: LIFO

LIFO: Last In First Out

Copyright © 直通硅⾕ Tower of Hanoi


http://www.zhitongguigu.com 4
Queue: FIFO

FIFO: First In First Out

5
Queue: FIFO
1

FIFO: First In First Out

5
Queue: FIFO
1 2

FIFO: First In First Out

5
Queue: FIFO
1 2 3

FIFO: First In First Out

5
Queue: FIFO
1 2 3 4

FIFO: First In First Out

5
Queue: FIFO
1 2 3 4 5

FIFO: First In First Out

5
Queue: FIFO
1 2 3 4 5

FIFO: First In First Out

6
Queue: FIFO
2 3 4 5

FIFO: First In First Out

6
Queue: FIFO
3 4 5

FIFO: First In First Out

6
Queue: FIFO
4 5

FIFO: First In First Out

6
Queue: FIFO
5

FIFO: First In First Out

6
Queue: FIFO

FIFO: First In First Out

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 {

private int size;


private int capacity;
private String[] elementData;

public Stack(int capacity_) {


size = 0;
capacity = capacity_;
elementData = new String[capacity];
}
}

9 . 2
Stack Implementation- Push
class Stack {

public String push(String item) {


if (size == capacity) {
resize();
}
elementData[size++] = item;
return item;
}
}

9 . 3
Stack Implementation- Pop
class Stack {

public String pop() {


if (size == 0) {
// throw Exception
}
String obj = elementData[--size];
return obj;
}
}

9 . 4
Stack Implementation- Peek
class Stack {

public String peek() {


if (size == 0) {
// throw Exception
}
return elementData[size - 1];
}
}

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 {

private int size;


private int capacity;
private int front;
private int rear;
private String[] elementData;

public Queue(int capacity_) {


capacity = capacity_;
size = 0;
front = 0;
rear = 0;
elementData = new String[capacity];
}

13 . 2
Queue Implementation - offer
class Queue {

public boolean add(String item) {


if (size == capacity) {
// throw Exception
} else {
elementData[rear] = item;
rear = (rear + 1) % capacity;
size++;
return true;
}
}
}

13 . 3
Queue Implementation - poll
class Queue {

public String poll() {


if (size == 0) {
// throw Exception
}
String obj = elementData[front];
front = (front + 1) % capacity;
size--;
return obj;
}
}

13 . 4
Queue Implementation - peek
class Queue {

public String element() {


if (size == 0) {
// throw Exception
}
return elementData[front];
}
}

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 {

Stack<Integer> stack1 = new Stack<Integer>();


Stack<Integer> stack2 = new Stack<Integer>();
}

16 . 3
Implement Queue using Stacks
class MyQueue {

public void push(int x) {


stack2.push(x);
}

public void pop() {


if(stack1.isEmpty()) {
while(!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
}
stack1.pop();
}

public int peek() {


if(stack1.isEmpty()) {
while(!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
}
return stack1.peek();
}
}

16 . 4
Implement Queue using Stacks
class MyQueue {

public void push(int x) {


stack2.push(x);
}

public void pop() {


reorder();
stack1.pop();
}

public int peek() {


reorder();
return stack1.peek();
}

private void reorder() {


if(stack1.isEmpty()) {
while(!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
}
}
}

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;

public MaxStack(int capacity) {


elements = new Stack<>(capacity);
maxElements = new Stack<>(capacity);
}

public int size() {


return elements.size();
}

public int pop() {


maxElements.pop();
return elements.pop();
}

public int max() {


return maxElements.peek();
}
}

17 . 3
Max Stack
class MaxStack {

public void push(int value) {


int currentMax;
if (elements.size() == 0) {
currentMax = Integer.MIN_VALUE;
} else {
currentMax = maxElements.peek();
}
elements.push(value);
if (currentMax > value) {
maxElements.push(currentMax);
} else {
maxElements.push(value);
}
}

public int peek() {


return elements.peek();
}
}

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

You might also like