DATA S T RU C T U R E -
II
Stack and Queues
S TA C K
A stack is a collection of data items that can be
accessed at only one end, called top.
Items can be inserted and deleted in a stack only
at the top.
The last item inserted in a stack is the first one
to be deleted.
Therefore, a stack is called a Last-In-First-Out
(LIFO) data structure.
2 mains operations on Stack is P U S H & POP
P U S H means inserting new item at top and POP
means deleting item from top.
OTHER STACK TERM
Peek : getting the most recent value of stack i.e
value at TOP
OverFlow : a situation when we are Pushing item
in Stack that is full.
Underflow : a situation when we are Popping
item from empty stack
IMPLEMENTING STACK IN
PYTHON This function will
check Stack is
empty or not
This function will
add new item in
Stack, here setting
top is mandatory
This function is used
to remove item from
stack, also perform
checks before deletion
IMPLEMENTING STACK IN
PYTHON This function will
return the top
most item from the
stack
This function will
display stack items
IMPLEMENTING STACK IN
PYTHON
Displaying menu
to user to interact
IMPLEMENTING STACK IN
PYTHON
QUEUE
Queue is a linear list which follows F I FO
approach.
Queue allows addition of element only at one end
called R E A R (end of list) & Deletion of element
only from F RO N T end (beginning of list).
The operation of addition and deletion is known
as Enqueue and Dequeue respectively.
Applications of Queue:
⚫ Printer Spooling
⚫ C P U Scheduling
⚫ Mail Service
⚫ Keyboard Buffering
⚫ Elevator
IMPLEMENTING Q U E U E IN
PYTHON
:: Peek
Q U E: U E OPERATIONS
getting first value of Q U::E U E i.e. of
F RO N T position.
e.g. Queue[Front] # Front is an int storing index of
first element of queue
Enqueue: addition of new item in Q U E U E at
R E A R position.
e.g. Queue.append(Item)
Dequeue: removal of item from the beginning of
QUEUE.
e.g. Queue.pop(0)
PYTHON CODE: Q U E U E
This function will
check Queue is
empty or not
This function will
add new item in
Queue, here setting
top is mandatory
This function is used
to remove item from
Queue, also perform
checks before deletion
PYTHON CODE: Q U E U E
This function will
return the Front
item from the
Queue
This function will
display Queue
items
PYTHON CODE: Q U E U E
Displaying menu
to user to interact
PYTHON CODE: Q U E U E
VARIATIONS OF QU E U E
Circular Queue : it is implemented in circular
form rather than straight line. It is used in many
programming language to overcome the problems
of linear queue (utilization of unused position in
the beginning).
Dequeue (Doubly-ended queue) : it is the form of
queue in which elements can be added or
removed from any end but not in the middle. It is
of 2 type: (1) Input restricted (2) Output
restricted
⚫ Input restricted means insertion only at one end but
deletion from both end
⚫ Output restricted means deletion from one end and
insertion from both end