Professional Documents
Culture Documents
Last-In-First-Out (LIFO)
Pop()
push(item)
Peek()
stack
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
b a
StackArr arr
0 1 2 3 4 5 6 7 8 9
push(F); push(G);
A
10 maxsize
pop();
top
StackLL
list
Top = Front of List BasicLinkedList head
num_nodes
4 a1 a2 a3 a4
Incorrect examples:
// too many close brackets // too many open brackets // mismatched brackets
[ ( [ {
] ) ] }
Stack
Terms
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
2 3 4 * +
10
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
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
/ e
6-10 Queues
First-In-First-Out (FIFO)
poll() offer(item)
Front of queue queue Back of queue
peek()
15
16
QueueArr arr
0 1 2 3 4 5 6 7 8 9
offer(F); offer(G);
A
10 maxsize
poll();
front
back
17
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
19
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
QueueLL
list
TailedLinkedList head
num_nodes
4 a1 a2 a3 a4
tail
21
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
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