You are on page 1of 23

1-5 Stacks

Last-In-First-Out (LIFO)

1 Stack ADT: Operations


A Stack is a collection of data that is accessed in a lastin-first-out (LIFO) manner Major operations: push, pop, and peek.
item

Pop()
push(item)

Peek()
stack

1 Stack ADT: Uses


Calling a function
Before the call, the state of computation is saved on the stack so that we will know where to resume

Recursion Matching parentheses Evaluating arithmetic expressions (e.g. a + b c) :


postfix calculation Infix to postfix conversion

Traversing a maze

1 Stack: Usage
Stack s = new Stack(); s.push (a); s.push (b); s.push (c); d = s.peek (); s.pop (); s.push (e); s.pop (); s d

c e

Q: Can a be replaced by a? A: Yes B: No

To be accurate, it is the references to a, b, c, , being pushed or popped.

b a

2 Stack Implementation: Array

Use an Array with a top index pointer

StackArr arr
0 1 2 3 4 5 6 7 8 9

push(F); push(G);

A
10 maxsize

pop();

top

3 Stack Implementation: Linked List

Method #1 (Composition): Use BasicLinkedList

StackLL

list
Top = Front of List BasicLinkedList head

num_nodes
4 a1 a2 a3 a4

5 Application 1: Bracket Matching

Ensures that pairs of brackets are properly matched


An example: {a,(b+f[4])*3,d+f[5]}

Incorrect examples:

(..)..) (..(..) [..(..]..)

// too many close brackets // too many open brackets // mismatched brackets

5 Application 1: Bracket Matching


create empty stack for every char read Q: What type of error does { the last line test for? if open bracket then A: too many closing brackets push onto stack B: too many opening brackets if close bracket, then C: bracket mismatch pop from the stack if doesnt match or underflow then flag error } if stack is not empty then flag error
Example { a -( b + f [ 4 ] ) * 3 * d + f [ 5 ] }

[ ( [ {

] ) ] }

Stack

5 Application 2: Arithmetic Expression

Terms

Expression: Operands: Operators:

a=b+c*d a, b, c, d =, +, , *, /, %

Precedence rules: Operators have priorities over one another as indicated in a table (which can be found in most books & our first few lectures)

Example: * and / have higher precedence over + and . For operators at the same precedence (such as * and /), we process them from left to right

5 Application 2: Arithmetic Expression


Infix Prefix Postfix - operand1 operator operand2 - operator operand1 operand2 - operand1 operand2 operator
Unique interpretation postfix 2 3 + 4 *

Ambiguous, need () or precedence rules infix 2+3*4 2+(3*4) (2+3)*4

2 3 4 * +
10

5 Application 2: Arithmetic Expression


Algorithm: Calculating Postfix expression with stack
Create an empty stack for each item of the expression, if it is an operand, push it on the stack if it is an operator, pop arguments from stack; perform the operation; push the result onto the stack Infix 2 * (3 + 4) postfix 2 3 4 + *

Stack

2 3 4 +

s.push(2) s.push(3) s.push(4) arg2 = s.pop () arg1 = s.pop () s.push (arg1 + arg2)
arg2 = s.pop () arg1 = s.pop () s.push (arg1 * arg2)

*
arg1

32
arg2

47

4 3 7 2 14

11

5 Application 2: Arithmetic Expression


Brief steps for Infix to Postfix Conversion
1. 2. 3. 4. Scan infix expression from left to right If an operand is found, add it to the postfix expression. If a ( is found, push it onto the stack. If a ) is found
a) repeatedly pop the stack and add the popped operator to the postfix expression until a ( is found.

b) remove the (.

5.

If an operator is found
a) repeatedly pop the operator from stack which has higher or equal precedence than/to the operator found, and add the popped operator to the postfix expression. b) add the new operator to stack

6.

If no more token in the infix expression, repeatedly pop the operator from stack and add it to the postfix expression.
12

5 Application 2: Arithmetic Expression (6/7)


Algorithm: Converting Infix to an equivalent Postfix
ch a ( b + c * d ) Stack (bottom to top) ( ( (+ (+ (+* (+* (+ ( / / postfixExp a a a ab ab abc abc abcd abcd* abcd*+ abcd*+ abcd*+ abcd*+e abcd*+e/ Example: a ( b + c * d ) / e

Move operators from stack to postfixExp until '('

/ e

Copy remaining operators from stack to postfixExp


13

6-10 Queues

First-In-First-Out (FIFO)

6 Queue ADT: Operations


A Queue is a collection of data that is accessed in a firstin-first-out (FIFO) manner Major operations: poll (or dequeue), offer (or enqueue), and peek.

poll() offer(item)
Front of queue queue Back of queue

peek()

15

6 Queue ADT: Uses


Print queue Simulations Breadth-first traversal of trees Checking palindromes - for illustration only as it is not a real application of queue

16

7 Queue Implementation: Array

Use an Array with front and back pointer

QueueArr arr
0 1 2 3 4 5 6 7 8 9

offer(F); offer(G);

A
10 maxsize

poll();

front

back

17

7 Queue Implementation: Array

CircularArray needed to recycle space


0 1 2 3 4 5 6 7 8 9

Given a queue
front

back
9 0

front
1

back

B C
2

To advance the indexes, use front = (front+1) % maxsize; back = (back+1) % maxsize;

G
6

F E
5 4

D
3

18

7 Queue Implementation: Array

Question: what does (front == back) mean?


A: Full queue B: Empty queue C: Both A and B D: Neither A nor B

19

7 Queue Implementation: Array

Ambiguous full/empty state


Queue Empty State
e f c d F B F B

Queue Full State

Solution 1 Maintain queue size or full status size 0 size

Solution 2 (Preferred and used in our codes) Leave a gap! Dont need the size field this way Full Case: (((B+1) % maxsize) == F) Empty Case: F == B
e c d B F

20

8 Queue Implementation: Linked List

Method #1 (Composition): Use TailedLinkedList

Do not use BasicLinkedList as we would like to use addLast() of TailedLinkedList.

QueueLL

list

TailedLinkedList head

num_nodes
4 a1 a2 a3 a4

tail

21

8 Queue Implementation: Linked List

Method #2 (Inheritance): Extend TailedLinkedList

For your information only. Inheritance is not covered by CS1020

QueueLLE

TailedLinkedList

head

num_nodes
4 a1 a2 a3 a4

tail

22

10 Application: Palindromes

A string which reads the same either left to right, or right to left is known as a palindrome

Palindromes: radar, deed, aibohphobia Non-palindromes: data, little


input

c1 c2 c3 c4 c5

Algorithm

Given a string, use: a Stack to reverse its order a Queue to preserve its order Check if the sequences are the same

top stack < c5, c4, c3, c2, c1 > Queue < c , c , c , c , c > 1 2 3 4 5 front tail
23

You might also like