Unit 3
Unit 3
Stacks and Queues: Introduction to stacks: properties and operations, implementing stacks
using arrays and linked lists, Applications of stacks in expression evaluation, backtracking,
reversing list etc.
Queues: Introduction to queues: properties and operations, implementing queues using arrays
and linked lists, Applications of queues in breadth-first search, scheduling, etc.
1) Stack
A Stack is a linear data structure that 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).
LIFO implies that the element that is inserted last, comes out first
and FILO implies that the element that is inserted first, comes out
last.
It behaves like a stack of plates, where the last plate added is the
first one to be removed. Think of it this way:
Popping an element means removes the top plate from the stack.
Push
Pop
Display
Peek
Before popping the element from the stack, we check if the stack
is empty.
Before returning the top element from the stack, we check if the
stack is empty.
a stack contains a top pointer. which is the “head” of the stack where
pushing and popping items happens at the head of the list. The first
node has a null in the link field and second node-link has the first
node address in the link field and so on and the last node address is
in the “top” pointer.
Note: The main advantage of using a linked list over arrays is that it
is possible to implement a stack that can shrink or grow as much as
needed.
Operations of stack
push(): Insert a new element into the stack i.e just insert a new element at the beginning of
the linked list.
pop(): Return the top element of the Stack i.e simply delete the first element from the linked
list.
peek(): Return the top element.
display(): Print all elements in Stack.
push operation:
Pop Operation:
First Check whether there is any node present in the linked
list or not, if not then return
Otherwise make pointer let say temp to the top node and move
forward the top node by 1 step
Now free this temp node
Peek Operation:
Check if there is any node present or not, if not then return.
Otherwise return the value of top node of the linked list
Display Operation:
Take a temp node and initialize it with top pointer
Now start traversing temp till it encounters NULL
Simultaneously print the value of the temp node
The elements of stack are 44 ->33 ->22 -> 11