Unit-3: Stacks and Queues: 2M Questions
Unit-3: Stacks and Queues: 2M Questions
2M Questions
8M Questions
1. Define stack. Implement push pop and display functions.
2. Different types of queue? list applications of queues.
3. Mention different ways to implement stack data structure. Write sample code for each method.
4. Implement queue using stack.
5. Implement Queue using Linked lists in Python.
6. Differentiate between Queue, Priority Queue and Deque.
7. Implement Stack using Linked list in Python.
8. Explain in detail about Deque with an example python program.
9. Implement priority and double ended queue in python
10. Convert following expression X+(Y * Z) – ((N * M +O) /Q) in to post fix form.
11. Differences between stacks and queues.
2M Questions
3. Define Stack
A)
A stack is an abstract data type that holds an ordered, linear sequence
of items. In contrast to a queue, a stack is a last in, first out (LIFO)
structure. A real-life example is a stack of plates: you can only take a plate
from the top of the stack, and you can only add a plate to the top of the
stack.
4. Define Queue
A)
A Queue is a FIFO (First In First Out) data structure where the element
that is added first will be deleted first. The basic queue operations are
enqueue (insertion) and dequeue (deletion).The elements in a queue are
arranged sequentially and hence queues are said to be linear data
structures.
5. Define dequeue
A)
A deque, also known as a double-ended queue, is an ordered collection of
items similar to the queue.In a sense, this hybrid linear structure provides
all the capabilities of stacks and queues in a single data structure.
Advantages :
Ease of insertion/deletion
Priority queue does not have any ends. In a priority queue, elements can
be inserted in any order but removal of the elements is in a sorted order.
15. Differentiate between stacks and Queues.
A)
STACK -
1) It is called as LIFO which stands for Last in first out as stack uses this
property.
2) Element inserted first will be accessed last in stack as it has only one
open end.
3) Example is plates placed one above other.
QUEUE -
1) It is called as FIFO which stands for First in first out as queue uses
these property.
2) Element inserted first will be served first.
3) Example is queue for bus.
8M Questions
1. Define stack. Implement push pop and display functions.
A)
A stack is a linear data structure that stores items in a Last-In/First-
Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new
element is added at one end and an element is removed from that
end only. The insert and delete operations are often called push and
pop.
Implementing push
def push(self, val):
self.data.append(val)
s.push(10)
s.push(100)
Implementing pop
def pop(self):
self.data.pop()
s1.pop()
Implementing display
Simple Queue
A simple queue is the most basic queue. In this queue, the enqueue
operation takes place at the rear, while the dequeue operation takes
place at the front:
Circular Queue
It’s used to switch on and off the lights of the traffic signal systems. Apart
from that, it can be also used in place of a simple queue in all the
applications mentioned above.
Priority Queue
A deque is also a special type of queue. In this queue, the enqueue and
dequeue operations take place at both front and rear. That means, we
can insert an item at both the ends and can remove an item from both the
ends. Thus, it may or may not adhere to the FIFO order:
Using array
def createStack():
stack = []
return stack
# Stack is empty when stack size is 0
def isEmpty(stack):
return len(stack) == 0
stack.append(item)
def pop(stack):
if (isEmpty(stack)):
return stack.pop()
def peek(stack):
if (isEmpty(stack)):
return stack[len(stack) - 1]
stack = createStack()
push(stack, str(10))
push(stack, str(20))
push(stack, str(30))
Output :
10 pushed into stack
20 pushed into stack
30 pushed into stack
30 Popped from stack
Top element is : 20
Elements present in stack : 20 10
class StackNode:
self.data = data
self.next = None
class Stack
def __init__(self):
self.root = None
def isEmpty(self):
newNode.next = self.root
self.root = newNode
def pop(self):
if (self.isEmpty()):
return float("-inf")
temp = self.root
self.root = self.root.next
popped = temp.data
return popped
def peek(self):
if self.isEmpty():
return float("-inf")
return self.root.data
# Driver code
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
Output:
10 pushed to stack
20 pushed to stack
30 pushed to stack
30 popped from stack
Top element is 20
Elements present in stack : 20 10
class Queue:
def __init__(self):
self.s1 = [ ]
self.s2 = [ ]
while len(self.s1) != 0:
self.s2.append(self.s1[-1])
self.s1.pop()
# Push item into self.s1
self.s1.append(x)
while len(self.s2) != 0:
self.s1.append(self.s2[-1])
self.s2.pop()
def deQueue(self)
if len(self.s1) == 0:
print("Q is Empty")
x = self.s1[-1]
self.s1.pop()
return x
# Driver code
if __name__ == '__main__':
q = Queue()
q.enQueue(1)
q.enQueue(2)
q.enQueue(3)
print(q.deQueue())
print(q.deQueue())
print(q.deQueue())
Output:
1
2
3
Method 2 (By making deQueue operation costly)In this method, in
en-queue operation, the new element is entered at the top of stack1.
In de-queue operation, if stack2 is empty then all the elements are
moved to stack2 and finally top of stack2 is returned.
class Queue:
def __init__(self):
self.s1 = [ ]
self.s2 = [ ]
self.s1.append(x)
print("Q is Empty")
return
while len(self.s1):
temp = self.s1.pop()
self.s2.append(temp)
return self.s2.pop()
else:
return self.s2.pop()
# Driver code
if __name__ == '__main__':
q = Queue()
q.enQueue(1)
q.enQueue(2)
q.enQueue(3)
print(q.deQueue())
print(q.deQueue())
print(q.deQueue())
Output:
123
Class Node:
self.data = data
self.next = None
class Queue:
def __init__(self):
temp = Node(item)
if self.rear == None:
return
self.rear.next = temp
self.rear = temp
def DeQueue(self):
if self.isEmpty():
return
temp = self.front
self.front = temp.next
if(self.front == None):
self.rear = None
# Driver Code
if __name__== '__main__':
q = Queue()
q.EnQueue(10)
q.EnQueue(20)
q.DeQueue()
q.DeQueue()
q.EnQueue(30)
q.EnQueue(40)
q.EnQueue(50)
q.DeQueue()
Output:
Queue Front : 40
Queue Rear : 50
class Stack:
if self.head == None:
self.head=Node(data)
else:
newnode = Node(data)
newnode.next = self.head
self.head = newnode
if self.isempty():
return None
else:
# Removes the head node and makes
#the preceeding one the new head
poppednode = self.head
self.head = self.head.next
poppednode.next = None
return poppednode.data
if self.isempty():
return None
else:
return self.head.data
iternode = self.head
if self.isempty():
print("Stack Underflow")
else:
while(iternode != None):
# Driver code
MyStack = Stack()
MyStack.push(11)
MyStack.push(22)
MyStack.push(33)
MyStack.push(44)
44->33->22->11->
Top element is 44
22->11->
Top element is 22
8. Explain in detail about Deque with an example python
program.
Deque (Doubly Ended Queue) in Python is implemented using the module
“collections“. Deque is preferred over list in the cases where we need quicker
append and pop operations from both the ends of container, as deque
provides an O(1) time complexity for append and pop operations as compared
to list which provides O(n) time complexity.
Example:
Python3
# Declaring deque
queue = deque(['name','age','DOB'])
print(queue)
Output:
deque(['name', 'age', 'DOB'])
Let’s see various Operations on deque :
append() :- This function is used to insert the value in its argument
to the right end of deque.
appendleft() :- This function is used to insert the value in its
argument to the left end of deque.
pop() :- This function is used to delete an argument from the right
end of deque.
popleft() :- This function is used to delete an argument from the left
end of deque.
Python3
# initializing deque
de = collections.deque([1,2,3])
de.append(4)
print (de)
de.appendleft(6)
print (de)
de.pop()
de.popleft()
print (de)
Output:
import collections
# initializing deque
de = collections.deque([1, 2, 3, 3, 4, 2, 4])
print (de.index(4,2,5))
de.insert(4,3)
print (de)
print (de.count(3))
de.remove(3)
# printing modified deque
print (de)
Output:
The number 4 first occurs at a position :
4
The deque after inserting 3 at 5th position is :
deque([1, 2, 3, 3, 3, 4, 2, 4])
The count of 3 in deque is :
3
The deque after deleting first occurrence of 3 is :
deque([1, 2, 3, 3, 4, 2, 4])
extend(iterable) :- This function is used to add multiple values
at the right end of deque. The argument passed is an iterable.
import collections
# initializing deque
de = collections.deque([1, 2, 3,])
de.extend([4,5,6])
print (de)
de.extendleft([7,8,9])
print (de)
# rotates by 3 to left
de.rotate(-3)
print (de)
# using reverse() to reverse the deque
de.reverse()
print (de)
Output :
The deque after extending deque at end is :
deque([1, 2, 3, 4, 5, 6])
The deque after extending deque at beginning is :
deque([9, 8, 7, 1, 2, 3, 4, 5, 6])
The deque after rotating deque is :
deque([1, 2, 3, 4, 5, 6, 9, 8, 7])
The deque after reversing deque is :
deque([7, 8, 9, 6, 5, 4, 3, 2, 1])
A)
Implement priority
# using Queue.
class PriorityQueue(object):
def __init__(self):
self.queue = []
def __str__(self):
def isEmpty(self):
return len(self.queue) == 0
self.queue.append(data)
def delete(self):
try:
max = 0
for i in range(len(self.queue)):
max = i
item = self.queue[max]
del self.queue[max]
return item
except IndexError:
print()
exit()
if __name__ == '__main__':
myQueue = PriorityQueue()
myQueue.insert(12)
myQueue.insert(1)
myQueue.insert(14)
myQueue.insert(7)
print(myQueue)
print(myQueue.delete())
Output:
12 1 14 7
14
12
7
1
double ended queue
Class: Deque
class Deque:
def __init__(self):
self.queue = [ ]
self.count = 0
def __repr__(self):
str = ""
if self.count == 0:
str += "Double Ended Queue Empty."
return str
str += "Double Ended Queue:\n" + self.queue.__repr__()
return str
self.queue.insert(0, data)
self.count += 1
return
self.queue.append(data)
self.count += 1
return
def remove_start(self):
if self.count == 0:
raise ValueError("Invalid Operation")
x = self.queue.pop(0)
self.count -= 1
return x
def remove_end(self):
if self.count == 0:
raise ValueError("Invalid Operation")
x = self.queue.pop()
self.count -= 1
return x
return self.queue[index]
def size(self):
return self.count
def display(self):
print(self)
return