Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret...
Transcript of Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret...
![Page 1: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/1.jpg)
Stacks
15-121 Fall 2020Margaret Reid-Miller
![Page 2: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/2.jpg)
Announcements
• Homework 7: due Tuesday Oct 27 at 11:55pm
• Quiz 7 due Sunday 11:55 pm Oct 22
• Early course feedback by Sunday 11:55 pm Oct 22
• Margaret Office Hours:• 10am-12pm Mondays• 4pm-5pm Thursdays
Fall 2020 15-121 (Reid-Miller) 2
![Page 3: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/3.jpg)
Today
• Finish using Iterators
• Stacks ADT (Queues next week)
• ArrayStack implemention
• Stack Applications
Fall 2020 15-121 (Reid-Miller) 3
![Page 4: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/4.jpg)
Interfaces reviewRecall SimplePlayer and RandomPlayer implement the Player interface.• Can we define more than one method in an
interface?• Can we write code in the Player interface?• Can SimplePlayer implement methods that don’t
appear in the Player interface?• What happens if we don’t write “implements Player” in the SimplePlayer class header?
We won’t be able to assign an instance of SimplePlayer to a variable of type Player.
YesNo
Yes
Fall 2020 15-121 (Reid-Miller) 4
![Page 5: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/5.jpg)
Interfaces review (cont’d)
• What if you say you implement Player but you don’t provide a remove method?
• Does the remove method in SimplePlayer have to be public?
• Can a class implement more than one interface?• Can we write a class that implements the Player
interface with a remove method that returns 3?Yes. The logic of the method is not enforced by the compiler. But we shouldn’t because it would violate the rules of the game.
• Can I write SimplePlayer sp = new Player();
YesYes
Won’t compile
NoFall 2020 15-121 (Reid-Miller) 5
![Page 6: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/6.jpg)
Iterators (cont'd)
![Page 7: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/7.jpg)
List<E> methods includes iterator()int size()boolean add(E obj)void add(int index, E obj)E get(int index)…Iterator<E> iterator()
returns an iterator object that implements the Iterator<E> interface
Fall 2020 15-121 (Reid-Miller) 7
![Page 8: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/8.jpg)
The Iterator interface
boolean hasNext()Returns true if there is another element to process.
E next()
Returns the next element. If there are no more elements, throws the NoSuchElementException.
void remove()Removes the last element returned by the next method. (Can only be call once after calling next.)
Fall 2020 15-121 (Reid-Miller) 8
![Page 9: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/9.jpg)
Careful: What will this code do?public static void remove(List<String> list,
String s) {Iterator<String> iter = list.iterator();int index = 0;while (iter.hasNext()) {
if (iter.next().equals(s))list.remove(index);
elseindex++;
}
CRASHES with ConcurrentModificationException
Lesson: Don't modify the collection except by using the iterator's remove method.
Fall 2020 15-121 (Reid-Miller) 9
![Page 10: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/10.jpg)
Use the iterator's remove method when using an iterator// Removes all occurrences of s from listpublic static void remove(List<String> list,
String s) {Iterator<String> iter = list.iterator();while (iter.hasNext()) {
if (iter.next().equals(s))iter.remove();
}
What is the runtime complexity?ArrayList: _________LinkedList: _________
Fall 2020 15-121 (Reid-Miller) 10
O(n)O(n2)
![Page 11: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/11.jpg)
Exercise: Count the number of times target appears in a list of strings.
public static int count(List<String> list, String target) {
Fall 2020 15-121 (Reid-Miller) 11
![Page 12: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/12.jpg)
Exercise: Count the number of times target appears in a list of strings.
public static int count(List<String> list, String target) {
int count = 0;Iterator<String> iter =
list.iterator();while (iter.hasNext()) {
if (target.equals(iter.next())) {count++;
}}
}
Fall 2020 15-121 (Reid-Miller) 12
![Page 13: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/13.jpg)
The Iterable interface
• If we have SinglyLinkedList implements Iterator, we can only have one iterator for the list.• That is, the singly-linked list class acts as the iterator
itself.
• Instead, SinglyLinkedList can implement Iterable, which means that the class has an inner class that implements Iterator and each instance of this inner class is an iterator object.• We can have more than one iterator for a list.
Fall 2020 15-121 (Reid-Miller) 13
![Page 14: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/14.jpg)
Iterable<T> interface
• Specifies an iterator method.Iterator<T> iterator()
• Implemented by the Collection interface.
• All classes that implement the Collection interface must include an iterator method that returns an Iterator for that collection.
• The enhanced for statement can then be used to "traverse" the collection one element at a time easily.
Fall 2020 15-121 (Reid-Miller) 14
![Page 15: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/15.jpg)
Example(using the enhanced for loop)
• Let myList be an ArrayList of Integer.• Since myList is an ArrayList, and ArrayList is a
subclass of Collection, it must have an iteratormethod that returns an iterator for the collection.
int total = 0;for (int nextInt : myList)
total += nextInt;
Fall 2020 15-121 (Reid-Miller) 15
implicitly instantiates an iterator and calls the hasNext and next methods;remove is not available
![Page 16: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/16.jpg)
Exercise: count (using the enhanced for loop)
public static int count(List<String> list, String target) {
int count = 0;for (String nextStr : list) {
if (target.equals(nextStr)) {count++;
}}
}
Fall 2020 15-121 (Reid-Miller) 16
![Page 17: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/17.jpg)
Example(using the enhanced for loop)
• Enhanced for loops can also be used with arrays.
int[] dataArray = new int[1000];...int total = 0;for (int nextInt : dataArray) {
total += nextInt;}
no index
Fall 2020 15-121 (Reid-Miller) 17
![Page 18: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/18.jpg)
Java ListIterator<E> interface• ListIterator is an extension of Iterator• Recall: The LinkedList class implements the List<E> interface using a doubly-linked list.
• Methods in ArrayList and LinkedList that return a list iterator:public ListIterator<E> listIterator()public ListIterator<E> listIterator(int index)
• Methods in the ListIterator interface:• add, hasNext, hasPrevious, next, previous, nextIndex, previousIndex, remove, set
Fall 2020 15-121 (Reid-Miller) 18
![Page 19: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/19.jpg)
Example: Replace a value in a list
Replace the first occurrence of target in LinkedListlist of strings with newItem :
ListIterator<String> iter =list.listIterator();
while (iter.hasNext()) {if (target.equals(iter.next())) {
iter.set(newItem);break;
}}
NOTE: You can use set, add, remove only once after next() or previous()
Fall 2020 15-121 (Reid-Miller) 19
![Page 20: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/20.jpg)
Fall 2020 15-121 (Reid-Miller) 20
![Page 21: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/21.jpg)
Stack ADT“last in, first out” (LIFO)
Operations:• PUSH – adds an element onto the top of the stack• POP – removes the element from the top of the stack• PEEK – returns the element on the top of the stack
without removing it (optional operation).• Test if the stack is EMPTY
Why have a Stack ADT?• Less power than arrays or Lists• Use them for more discipline, simple, fast operationsFall 2020 15-121 (Reid-Miller) 21
![Page 22: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/22.jpg)
Stack“last in, first out” (LIFO)
Uses:• A word processor’s “undo” feature• Parenthesis balancing• Evaluating subexpressions, like: 2*4 + 6*3• The run-time stack (activation records/stack frames)
Fall 2020 15-121 (Reid-Miller) 22
![Page 23: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/23.jpg)
Possible interface for Stackpublic interface LIFOStack<E> {
void push(E obj);E pop();E peek();boolean isEmpty();
}
Fall 2020 15-121 (Reid-Miller) 23
![Page 24: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/24.jpg)
Stack Implementations
Want O(1) for all operations, so what underlying data structure can we use?• array?
Yes, if top is last element of array• ArrayList?
Yes, if top is size()-1• linked list?
Yes, with top at head of the list
Fall 2020 15-121 (Reid-Miller) 24
![Page 25: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/25.jpg)
ArrayStack Implementation fields
public class ArrayStack<E> implements LIFOStack<E>{
private E[] dataArray;private int top;
// methods (next slide)
}
Fall 2020 15-121 (Reid-Miller) 25
Index of top stack element in array
![Page 26: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/26.jpg)
ArrayStack ImplementationConstructor & isEmpty
public ArrayStack<E>() {dataArray = (E[]) new Object[1];top = ___;
}
public boolean isEmpty() {return (__________);
}
Fall 2020 15-121 (Reid-Miller) 26
Indicates an empty stack
-1
top == -1
![Page 27: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/27.jpg)
ArrayStack Implementationpush
public void push(E obj) {if (___________________________)
grow();top = top + 1;dataArray[top] = obj;
}
Fall 2020 15-121 (Reid-Miller) 27
top == dataArray.length - 1
![Page 28: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/28.jpg)
ArrayStack Implementationpop
public E pop() {if (_________)
throw new EmptyStackException();E obj = dataArray[top];dataArray[top] == null;top--;return obj;
}
Fall 2020 15-121 (Reid-Miller) 28
top < 0
![Page 29: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/29.jpg)
ArrayStack Implementationpeek
public E peek() {if (top < 0)
throw new EmptyStackException();return dataArray[top];
}
Fall 2020 15-121 (Reid-Miller) 29
![Page 30: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/30.jpg)
Nested ParenthesesGoal: Determine if a string containing a mathematical expression is nested correctly.• String has only parenthetical symbols, include {}, [], ().Algorithm:• Process the expression from left to right.
• If left parenthetical symbol, push it on the stack.• If right parenthetical symbol, pop the stack to see if it is
a matching left parenthetical symbol.If not, the parenthetical nesting is invalid.
• When done processing the expression, if the stack is empty, the parenthetical nesting is valid.
Fall 2020 15-121 (Reid-Miller) 30
![Page 31: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/31.jpg)
Nested Parentheses: Example 1
E.g., { [ ( ) ] { } }
Fall 2020 15-121 (Reid-Miller) 31
Stack:{
{
{[
[
{[(
(
{[
)
{
]
{{
{
{
}Input: }
if left: pushif right: pop and check pair matches
![Page 32: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/32.jpg)
Nested Parentheses: Example 2
E.g, [ { ( } ) ]
[ [{
[{(
[{ ERROR:
doesn’t match with input }
Fall 2020 15-121 (Reid-Miller) 32
Stack:
Input: [ { ( }
(
![Page 33: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/33.jpg)
Nested Parentheses• What if there are too many LEFT symbols?
Stack will not be empty at the end.
• What if too many RIGHT symbols?You will try to pop an empty stack
• How can you determine if left and right symbols match?Trick:
left = "([{" right = ")]}"
Use indexOf to see if they have the same index.
Fall 2020 15-121 (Reid-Miller) 33
![Page 34: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/34.jpg)
Java maintains a run-time stack during the execution of your program.
• Each call to a method generates an activation frame that includes storage for:• arguments to the method• local variables for the method• return address of the instruction that called the method
• A call to a method pushes an activation record on the run-time stack.
• A return from a method pops an activation record from the run-time stack.
Fall 2020 15-121 (Reid-Miller) 34
![Page 35: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/35.jpg)
Run-Time Stack & Activation Frames❶ System.out.println(A(3));
public int A(int w) {❷ int x = B(w+1);
return x*4;}public int B(int x) {
❸ int y = C(x+1, x+2);return y*3;
}public int C(int y1, int y2) {
int z = y1 + y2;return z*2;
} rest of run-time stack
Activationrecord formethod C
y1 5y2 6z ret addr❸
Activationrecord formethod Bx 4
y ret addr❷
w 3x ret addr❶
Activationrecord formethod A
Fall 2020 15-121 (Reid-Miller) 35
![Page 36: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/36.jpg)
Some modern calculators use Postfix Expressions instead of Infix• Also, known as Reverse Polish Notation (RPN)
Fall 2020 15-121 (Reid-Miller) 36
• Developed in 1920 by Jan Łukasiewicz
• Can write mathematical formulas without using parentheses.
• Example:5 * ( 6 + 7 )becomes in RPN:5 6 7 + *
![Page 37: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/37.jpg)
Evaluating postfix with a stackNote: Assume the postfix expression is valid.
Each entry in a postfix expression is a token.1. Let S be an empty stack.2. For each token in the expression:
a. If the token is a number, push it on the stack S.b. Otherwise (the token is an operator):
i. Pop a token off stack S and store it in y.ii. Pop a token off stack S and store it in x.iii. Evaluate x operator y.iv. Push result on stack S.
3. Pop the stack for the final answer.
Fall 2020 15-121 (Reid-Miller) 37
![Page 38: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/38.jpg)
Evaluating postfix: Example• Postfix (RPN): 5 7 + 8 6 - / 3 9 * +
Fall 2020 38
input57+86-/39*+
stack |5|5 7|12|12 8|12 8 6|12 2|6|6 3|6 3 9|6 27|33
15-121 (Reid-Miller)
![Page 39: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/39.jpg)
Converting Infix to PostfixNote: Assume the infix expression is valid.
Each entry in a infix expression is a token.1. Let S be an empty stack (for operators).2. Let postfix be an empty string.3. For each token in the infix expression:
a. If the token is a number, append it to the postfix string.
b. Otherwise (the token is an operator) Process the operator (see next 2 slides)
4. While the stack S is not empty:a. Pop an operator off the stack S and append it to
the postfix string.Fall 2020 15-121 (Reid-Miller) 39
![Page 40: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/40.jpg)
Processing the operators(converting infix to postfix, cont’d)
• Each operator has a precedence.*, / multiplicative higher precedence+, - additive lower precedence
• Operators of the same precedence are evaluated left to right
• Assign precedence values to each operator.
• We put operators on the the stack only if precedence is increasing.
Fall 2020 15-121 (Reid-Miller) 40
Operator Precedence
* 2
/ 2
+ 1
- 1
![Page 41: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/41.jpg)
Process the operator(converting infix to postfix, cont’d)
Let nextOp be the operator token.1. If stack S is empty, push nextOp on stack S.2. Otherwise:
a. Let topOp = peek(S).b. If prec(nextOp) > prec(topOp), push nextOp on stack S.c. Otherwise:
i. While S is not empty and prec(nextOp) ≤ prec(topOp):a) Let topOp = pop(S).b) Append topOp to postfix string.c) If stack S is not empty, let topOp = peek(S).
ii. Push nextOp on stack S.
Fall 2020 15-121 (Reid-Miller) 41
![Page 42: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/42.jpg)
Converting: An example• Infix: 5 + 4 * 3 / 2 - 1
Fall 2020 15-121 (Reid-Miller) 42
![Page 43: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/43.jpg)
Converting Infix to Postfix: Infix: 5 + 4 * 3 / 2 – 1
input5+4*3/
2-
1
Fall 2020 43
stack postfix expression| 5|+
5 4|+ *
5 4 3|+ 5 4 3 *|+ /
5 4 3 * 2|+ 5 4 3 * 2 / | 5 4 3 * 2 / + |-
5 4 3 * 2 / + 1 | 5 4 3 * 2 / + 1 -
15-121 (Reid-Miller)
![Page 44: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/44.jpg)
Processing Parentheses(converting infix to postfix, cont’d)
• Each pair of parentheses marks a subexpression that must be completely converted before previous operators are processed.
Fall 2020 15-121 (Reid-Miller) 45
• Assign the lowest precedence to left and right parentheses so only a right parenthesis can pop off a left parenthesis.
• Do not put parentheses in the postfix string.
Operator Precedence
* 2
/ 2
+ 1
- 1
( -1
) -1
![Page 45: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/45.jpg)
Process the operator - revised(converting infix to postfix, cont’d)
Let nextOp be the operator token.1. If stack S is empty or nextOp is (, push nextOp on stack S.2. Otherwise:
a. Let topOp = peek(S).b. If prec(nextOp) > prec(topOp), push nextOp on stack S.c. Otherwise:
i. While S is not empty and prec(nextOp) ≤ prec(topOp):a) Let topOp = pop(S).b) If topOp is (, exit loop immediately. i.e., nextOp must be )c) Append topOp to postfix string.d) If stack S is not empty, let topOp = peek(S).
ii. If nextOp is not ), push nextOp on stack S.
Fall 2020 15-121 (Reid-Miller) 46
![Page 46: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/46.jpg)
Converting: An example• Infix: 7 + 5 * ( 4 / 2 + 1) - 6
Fall 2020 15-121 (Reid-Miller) 47
![Page 47: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/47.jpg)
Converting Infix to Postfix: Infix: 7 + 5 * ( 4 / 2 + 1) - 6
input7+5*(4/2+1)-6
Fall 2020
stack postfix expression| 7| +
7 5| + *| + * (
7 5 4| + * ( /
7 5 4 2| + * ( + 7 5 4 2 /
7 5 4 2 / 1| + * 7 5 4 2 / 1 +| - 7 5 4 2 / 1 + * +| 7 5 4 2 / 1 + * + 6 -
15-121 (Reid-Miller) 48
![Page 48: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/48.jpg)
Invalid expressions• Assume that tokens are only operators and integers.• Evaluating a postfix expression:
• How would you know that the postfix expression is not valid?
• Converting an infix expression to postfix:• How would you know that the infix expression is
not valid?
Fall 2020 15-121 (Reid-Miller) 49
![Page 49: Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret Reid-Miller. Today Exam 2 is Tuesday, Nov4 Today: •Quiz •Recursive add from lastclass(see](https://reader034.fdocuments.net/reader034/viewer/2022043012/5fab65d60c5d5b760b43aad8/html5/thumbnails/49.jpg)
Other uses for stacks
• Computing a convex hull• Backtracking through a problem space
(e.g. maze)• Parsing algorithms in a compiler• Machine language architecture
• Java Virtual Machine
Fall 2020 15-121 (Reid-Miller) 50