Stack and Queue
03/27/2025 1
Stacks and queues
03/27/2025 2
Stack
• An ordered collection of
homogeneous data elements where
insertion and deletion operations
take place at one end only
• Insertion: PUSH
• Deletion : POP
• Operation occur at TOP
• An element is termed as ITEM
• Maximum elements: SIZE of stack
• Data is processed as LIFO
03/27/2025 3
Stack Representation in Memory
• Single dimension array
• Empty: TOP<l (lower index)
• Full: Top=u (upper most index)
• Linked list
• Push at the front
• Pop from the front
• Size of the stack is not important here.
03/27/2025 4
Stack Operations of: PUSH
Array Linked List
• Method: • Method
{
{
If TOP=SIZE
New=getnode()
Stack is full
Else
NewDATA=ITEM
{ NewLINK=TOP
TOP=TOP+1 TOP=new
A[TOP]=ITEM STACK_HEADERLINK=TOP
} }
}
03/27/2025 5
Stack Operations: POP
Array Linked List
• Method • Method
{ {
If TOP==NULL
If TOP<l
Stack is empty
Stack is empty Else
Else {
{ Ptr=TOPLINK
ITEM=A[TOP] ITEM=TOPDATA
STACK_HEADERLINK=ptr
TOP=TOP-1
TOP=ptr
} }
} }
03/27/2025 6
Application of Stacks:
• Evaluation of Arithmetic operations
• Code generation for stack machines
• Implementation of recursion
• Factorial calculation
• Quick sort
• Tower of Hanoi: transfer items in ascending order to another stack
• Implementation of scope rules
03/27/2025 7
Assignment
• With relevant examples, demonstrate Infix, prefix
(Polish) and postfix (reverse polish) notations.
• Use postfix notation to evaluate any arithmetic
expression with the aid of a stack data structure
03/27/2025 8
Queue
• An ordered collection of
homogeneous data elements
where insertion and deletion
take place at extreme ends
• Insertion: ENQUEUE at REAR
• Deletion: DEQUEUE at FRONT
• Number of elements:
LENGTH
• Data is processed in FIFO
03/27/2025 9
Representation
• Array
• One dimension array
• Queue empty: FRONT=0, REAR=0
• Queue is full: FRONT=1, REAR=N
• Queue contains elements:
FRONT<=REAR
• Number of elements=REAR – FRONT + 1
• Linked List
• Queue empty: FRONT=REAR=HEADER,
HEADERLINK=NULL
• Queue contains elements:
HEADERLINK≠NULL
• Number of elements=REAR – FRONT + 1
03/27/2025 10
Queue Operations.
• Enqueue
• Dequeue
• Stutus: full, empty
03/27/2025 11
Types
• Normal queue
• Circular queue
• Priority queue
• Single entry, multiple exit queue
• Multiple entry and single exit queue
• Multiple entry (M) and multiple exits (N) where M≠N
03/27/2025 12
Application of queues
• Simulation; average: queue time, length, total service time
• CPU Scheduling in multiprogramming environment
• Round Robin algorithm
03/27/2025 13