Stacks and GATE PYQs
Mohd Ayyoob
(M.Tech CSA, IISc Banglore)
Abstract Data Types : STACKS & QUEUES
Stack Implementation using Array
Stack Implementation using Array
Stack Implementation using LIST
1. Initialise stack stack = [ ]
2. Implement push(elem) def push(elem):
stack.append(elem)
def pop():
3. Implement pop()
if len(stack) == 0:
print(“Underflow error”)
return
stack.pop()
Stack Implementation using Linked List
Stack Implementation using Linked List
Stack Implementation using Linked List
Stack Implementation using Linked List
Stack Implementation using Linked List
Stack Implementation using Linked List
Stack Implementation using Linked List
Stack Implementation using Linked List
Push : insert at front or beginning of the linked list
Pop : delete at front or beginning of the linked list
Stack Implementation using Linked List
Push(element)
1. Create Node new_elem = Node(val)
2. Insert @ begin of SLL new_elem.next = head
head = new_elem
Pop()
1. Delete @ begin of SLL temp = head
head = head.next
Stack Implementation using Linked List
Push(element)
1. Create Node new_elem = Node(val)
2. Insert @ begin of SLL new_elem.next = head
head = new_elem
Pop()
1. Delete @ begin of SLL temp = head
head = head.next
Stack Implementation using Linked List
Push(element)
1. Create Node new_elem = Node(val)
2. Insert @ begin of SLL new_elem.next = head
head = new_elem
Pop()
1. Delete @ begin of SLL temp = head
head = head.next
temp = None // NEW
Stack Implementation using Linked List
Push(element)
1. Create Node new_elem = Node(val)
2. Insert @ begin of SLL new_elem.next = head
head = new_elem
Pop()
1. Delete @ begin of SLL temp = head
head = head.next head = head.next
temp = None // NEW
Push (elem) :
1. Push to main stack
2. Check if the element that was added is <= top of minStack
if yes: push also into minStack
else: nothing
Pop ( ) :
1. Pop from main stack
2. if popped element is equal to top of minStack, pop from
min stack also
We are aware about a special stack implementation which performs getmin() operation in O(1) time and using an
extra stack i.e O(1) time and O(n) space where n is number of elements in stack. Can you think of the worst case?