Professional Documents
Culture Documents
Stack
Stack
What is Stack?
Stack is a linear data structure which follows a particular
order in which the operations are performed. The order
may be LIFO(Last In First Out) or FILO(First In Last
Out).
2
Stack ADT
Features/Operation
3
Stack ADT
A list with restriction that Operation:
insertion and deletion can be Push(x)
performed only from one end,
Pop()
called the top
Top()
IsEmpty()
4
Stack ADT
Push(2) Operation:
Push(5)
Push(x)
Pop()
Push(10) Pop()
Push(7) Top()
Top() => 7 IsEmpty()
7
IsEmpty() => false
10
5 Pop()
2 Pop()
Pop()
5
Stack ADT
Push(2) Operation:
Push(5)
Push(x)
Pop()
Push(10) Pop()
Push(7) Top()
Top() => 7 IsEmpty()
7
IsEmpty() => false
10 Pop()
2 Pop()
Pop()
6
Stack ADT
Applications:
- Function calls / Recursion
- Undo in an editor
- Balanced parenthesis
7
Implementation of
Stack
Stack ADT
A list with restriction that
insertion and deletion can be Push(x)
performed only from one end,
Pop()
called the top
Top()
Implement stack using : IsEmpty()
Arrays
Linked Lists
9
Array implementation of stack
top
Int A[10]
0 1 2 3 4 5 6 7 8 9
Top = -1 // empty stack
Push (x)
{
Top = Top + 1
A[Top] = x
}
10
Array implementation of stack
top
top
Int A[10]
2
Top = -1 // empty stack 0 1 2 3 4 5 6 7 8 9
Int A[10]
2 5 9
Top = -1 // empty stack 0 1 2 3 4 5 6 7 8 9
2 5 9
0 1 2 3 4 5 6 7 8 9
Push (2)
Pop ()
{ Push (5)
Top = Top - 1 Push (9)
} Pop ()
13
Array implementation of stack
top top
2 5 7
9
0 1 2 3 4 5 6 7 8 9
Push (2)
Pop ()
{ Push (5)
Top = Top - 1 Push (9)
} Pop ()
Push (7)
14
Array implementation of stack
top
2 5 7
0 1 2 3 4 5 6 7 8 9
Push (2)
Pop ()
Push (5)
{
Push (9)
Top = Top - 1
} Pop ()
Push (7)
15