- Sections 15.5-15.6

- Last-in first-out
- Can only access top element
- Operations push, pop, isEmpty

- First-in first-out
- Can only add to tail, remove from head
- Operations add, remove, isEmpty

`Stack<Integer> s = new Stack<>();` |
Constructs an empty stack. |

`s.push(1);` |
Adds to the top of the stack; `s` is now `[1, 2, 3]` . (Following the `toString` method of the `Stack` class, we show the top of the stack at the end.) |

`int top = s.pop(); ` |
Removes the top of the stack; `top` is set to 3 and `s` is now `[1, 2]` . |

`head = s.peek(); ` |
Gets the top of the stack without removing it; `head` is set to 2. |

`boolean b = s.empty()` |
Sets `b` to false. Same as `s.size() == 0` . |

`Queue<Integer> q = new LinkedList<>(); ` |
The LinkedList class implements the Queue interface. |

`q.add(1); q.add(2); q.add(3); ` |
Adds to the tail of the queue; `q` is now `[1, 2, 3]` |

`int head = q.remove(); ` |
Removes the head of the queue; `head` is set to 1 and `q` is `[2, 3]` |

`head = q.peek(); ` |
Gets the head of the queue without removing it; `head` is set to 2. |

`boolean b = s.empty()` |
Sets `b` to false. Same as `s.size() == 0` . |

- Add elements in any order
- Remove the most urgent one
*Not*a queue!

`PriorityQueue<Integer> q = new PriorityQueue<>(); ` |
This priority queue holds Integer objects. In practice, you would use objects that describe tasks. |

`q.add(3); q.add(1); q.add(2); ` |
Adds values to the priority queue. |

`int first = q.remove(); ` |
Each call to remove removes the most urgent item: `first` is set to 1, `second` to 2. |

`int next = q.peek(); ` |

What does this code print?

Stack<Integer> s = new Stack<>(); Queue<Integer> q = new LinkedList<>(); PriorityQueue<Integer> p = new PriorityQueue<>(); s.push(1); s.push(3); s.push(2); while (s.size() > 0) q.add(s.pop()); while (q.size() > 0) p.add(q.remove()); while (p.size() > 0) System.out.print(p.remove() + " ");

- 1 3 2
- 1 2 3
- 3 2 1
- 2 3 1

- Easy to check whether parentheses are balanced
- Example: -(b * b - (4 * a * c ) ) / (2 * a)
- Increment counter at (, decrement at )
- Counter must be 0 at end and never < 0 in the middle
- What if we have different kinds of parentheses?
- –{ [b ⋅ b - (4 ⋅ a ⋅ c ) ] / (2 ⋅ a) }
- Push them on a stack

while more tokens t = next token if t is an opening parenthesis stk.push(t) else if t is a closing parenthesis if stk is empty return false // 1 if t doesn't match stk.pop() return false // 2 return stk is empty // 3

For each of these three inputs, in which return statement does the algorithm return `false`

?

–{ [b ⋅ b - (4 ⋅ a ⋅ c ) ] / (2 ⋅ a) } ) –{ { [b ⋅ b - (4 ⋅ a ⋅ c ) ] / (2 ⋅ a) } –{ [b ⋅ b - (4 ⋅ a ⋅ c ) ] / (2 ⋅ a) ) }

- 1, 2, 3
- 1, 3, 2
- 2, 1, 3
- Something else

- Infix operators need parentheses to specify what comes first: (3 + 4) * 5
- Polish notation: Write operator before operands
- * + 3 4 5
- Invented by the Polish mathematician Jan Łukasiewicz
- Reverse Polish: Write them after the operand
- 3 4 + 5 *
- Used in classic pocket calculators and the Java virtual machine

while more tokens t = next token if t is a number stk.push(t) else if t is an operand arg2 = stk.pop() arg1 = stk.pop() result = apply operand to arg1 and arg2... stk.push(result) print(stk.pop())

What is the result of the Reverse Polish expression

2 1 3 + * 4 -

- 4
- -4
- 7
- None of the above

How do you write (3 + 4) x 5 + 6 in Reverse Polish?

- 3 4 5 x + 6 +

- 3 4 + 5 x 6 +

- 3 + 4 5 x + 6

- None of the above

- Regular notation, not reverse polish
- Push numbers on one stack, operators on another

- Core step—evaluating the top:

- Pop two numbers
- Pop an operator
- Apply operator to numbers
- Push the result

Number stack

Operator stack

Unprocessed input

Comments

3 + 4

3

+ 4

3

+

4

4

3

+

No more input

Evaluate the top

7

The result is 7

- * has higher precedence than +
- * and / have the same precedence
- Don't push an operator if it has higher precedence than the top operator. Instead, evaluate the top.

Number stack

Operator stack

Unprocessed input

Comments

3 * 4 + 5

3

* 4 + 5

3

*

4 + 5

4

3

*

+ 5

* has higher precedence

Evaluate the top

12

+

5

Now push +

5

12

+

No more input

Evaluate the top

17

The result is 17

- Push (
- When encountering a ), evaluate the top until the ( reappears
Number stack

Operator stack

Unprocessed input

Comments

3 * (4 + 5)

3

* (4 + 5)

3

*

(4 + 5)

(

*

4 + 5)

4

3

(

*

+ 5)

4

3

+

(

*

5)

5

4

3

+

(

*

)

9

3

(

*

No more input

Evaluate the top

9

3

*

Pop matching (

27

Evaluate the top—the result is 27

while more tokens t = next token if t is a number nums.push(t) else if t == "(" ops.push(t) else if t is an operator while ops.top() has a higher precedence than op Evaluate the top... ops.push(t) else if t == ")" while ops.top() != "(" Evaluate the top... ops.pop() while top not empty Evaluate the top...

- Escaping from a maze

- Use a stack to remember all paths that still need to be tried
- At an intersection, push all paths
- Pop one and follow it
- When a path is a dead end, pop the next one (that's the backtracking)

- Repeat until exit
- Can use a queue as well, but not as intuitive (you don't just go back to the last choice)

Push all paths from the point on which you are standing onto stk... While stk not empty p = stk.pop() pos = follow p until you reach an exit, intersection, or dead end... If pos is an exit Congratulations! Else if pos is an intersection Push all paths meeting at the intersection, except for p, onto stk

Recursion haters rejoice: you can always turn a recursion into an algorithm that uses a stack or queue.

Remember the number puzzle? Here it is without recursion.

q.add(puzzle) while q not empty p = q.remove() if p is solved add p to result else f = p.firstLetter() if f is not empty for i = 0 ... 9 if p doesn't contain i pnew = p.replace(f, i) q.add(pnew)

Change the solution to Homework 5c into this algorithm.

What is the first solution that is displayed?

- 3665+8699=12364
- 7886+4899=12785
- Something else
- Nothing is displayed—I think I got into an infinite loop

In the preceding question, replace the queue with a stack.

Tip—you can leave the calls to `add`

since `push`

and `add`

do the same thing.

Does it still work?

- No way—you can't just change a queue into a stack
- Yes, and the result is exactly the same
- Yes, and the result is in reverse order
- I got a stack overflow