Professional Documents
Culture Documents
Dsa ch5 Stack
Dsa ch5 Stack
Chapter 5:
Stack
Imran Ali Memon
IT Department
Contents
5.1 - Introduction
5.2 – Basic Operations
5.3 – Types of representation of stack in memory
5.4 – Push( ) Algorithm
5.5 – Pop( ) Algorithm
Introduction
Stack: (LIFO)
• A stack is a list of elements in which an element may
be added or deleted only at one end, called the top of
the stack.
• Anything added to the stack goes on the “top” of the
stack.
• Anything removed from the stack is taken from the
“top” of the stack.
• Things are removed in the reverse order from that in
which they were inserted (LIFO:Last In, First Out)
• Other names for stacks are piles and push-down lists.
Stack (LIFO)
Stack
AA BB CC DD
0 1 2 3 4 5 …… N-1 N
0 AA N
1 BB N-1
2 CC .
3 DD TOP
.
4 5
5 4
Count = 4
. 3 DD
Top = 3
. CC
2
N-1 BB
1
N 0 AA
Basic Operations
• There are two basic operations associated with
stack:
1. Push() is the term used to insert/add an element
into a stack.
2. Pop() is the term used to delete/remove an
element from a stack.
Push()
Pop()
The Towers of Hanoi
A Stack-based Application
CCC 3901
2000
TOP = 3901
BBB 2000
Count = 4
1050
AAA 1050
1001
1001
Head
Linked List Representation of Stack (Dynamic)
NEW 2100
BBB 1050
2000 1050 BBB 2000 1050
Head
Linked List Representation of Stack (Dynamic)
BBB 1050
2000 1050
AAA 1050 1001
1001
Count = 4 3 Head
Head
Array Representation of Stacks
• Usually the stacks are represented in the computer
by a linear array.
• In the algorithms of pushing and popping an item
from the stacks, we have considered,
• A linear array STACK,
• A variable TOP which contain the location of the
top element of the stack
• A variable STACKSIZE / MAXSTACK which gives the
maximum number of elements that can be hold by
the stack.
Stacks conditions
• The condition Top = -1 / Null indicate that the stack is empty.
• The condition Top = 8 indicate that the stack is full.
• It will be overflow if Top = 8 & push() will be performed.
• It will be underflow if Top = -1 & pop() will be performed.
Array Representation of Stacks
Stack conditions
1 CC 1 CC 1
0 BB 0 BB 0