Stacks - cs.cmu.edumrmiller/15-121/Slides/16-stacks.pdf · Stacks 15-121 Fall 2019 Margaret...

49
Stacks 15-121 Fall 2020 Margaret Reid-Miller

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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