Information on stacks as a linear data structure with a top and bottom end, where additions and removals only occur at the top. The document also covers the concept of parentheses matching using stacks, scanning expressions from left to right and adding or removing positions accordingly. Examples and recursive solutions for towers of hanoi/brahma problem are included.
Download Data Structures: Stacks and Parentheses Matching and more Slides Computer Science in PDF only on Docsity!
Stacks
Linear list.
One end is called top.
Other end is called bottom.
Additions to and removals from the top end
only.
Stack Of Cups
Add a cup to the stack.
bottom
top
C
A
B
D
E
F
Remove a cup from new stack.
A stack is a LIFO list.
bottom
top
C
A
B
D
E
Parentheses Matching
(((a+b)c+d-e)/(f+g)-(h+j)(k-l))/(m-n)
Output pairs (u,v) such that the left parenthesis at position u is matched with the right parenthesis at v. - (2,6) (1,13) (15,19) (21,25) (27,31) (0,32) (34,38)
(a+b))*((c+d)
(0,4)
right parenthesis at 5 has no matching left parenthesis
(8,12)
left parenthesis at 7 has no matching right parenthesis
Parentheses Matching
scan expression from left to right
when a left parenthesis is encountered, add its
position to the stack
when a right parenthesis is encountered, remove
matching position from stack
Example
(((a+b)c+d-e)/(f+g)-(h+j)(k-l))/(m-n)
Example
(((a+b)c+d-e)/(f+g)-(h+j)(k-l))/(m-n)
Example
(((a+b)c+d-e)/(f+g)-(h+j)(k-l))/(m-n)
and so on
Towers Of Hanoi/Brahma
A B C
1
2
3
4
64 gold disks to be moved from tower A to tower C
each tower operates as a stack
cannot place big disk on top of a smaller one Docsity.com
Towers Of Hanoi/Brahma
3-disk Towers Of Hanoi/Brahma
A B C
1
2 3
Towers Of Hanoi/Brahma
3-disk Towers Of Hanoi/Brahma
A B C
1 2 3
Towers Of Hanoi/Brahma
3-disk Towers Of Hanoi/Brahma
A B C
2 1
3
Towers Of Hanoi/Brahma
3-disk Towers Of Hanoi/Brahma
A B C
3 2 1
Towers Of Hanoi/Brahma
3-disk Towers Of Hanoi/Brahma
A B C
1
2
3
7 disk moves Docsity.com
Recursive Solution
A B C
1
n > 0 gold disks to be moved from A to C using B
move top n-1 disks from A to B using C Docsity.com