[go: up one dir, main page]

0% found this document useful (0 votes)
2K views33 pages

Unit-3: Stacks and Queues: 2M Questions

The document discusses different data structures and algorithms topics. It includes questions about the differences between various data structures like stacks and queues. It asks to implement sorting algorithms like bubble sort, insertion sort and selection sort on sample data. It also asks to calculate the number of iterations taken for linear and binary search on a given list. Finally, it provides multiple choice questions about applications and implementations of stacks, queues and other data structures. It asks to write programs for various operations on stacks and queues using linked lists.

Uploaded by

sirisha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views33 pages

Unit-3: Stacks and Queues: 2M Questions

The document discusses different data structures and algorithms topics. It includes questions about the differences between various data structures like stacks and queues. It asks to implement sorting algorithms like bubble sort, insertion sort and selection sort on sample data. It also asks to calculate the number of iterations taken for linear and binary search on a given list. Finally, it provides multiple choice questions about applications and implementations of stacks, queues and other data structures. It asks to write programs for various operations on stacks and queues using linked lists.

Uploaded by

sirisha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

11. a) Differences between Linear and Binary search.

b) Differences between Doubly and Circular Linked Lists.


12. Perform bubble sort on these numbers( 10,2,4,8,5,12,11) and write a program for the bubble sort
13. Perform bubble sort on these numbers( 20,13,6,8,1,19,3) and write a program for the Insertion sort
14. Perform bubble sort on these numbers(9,3,7,12,8,11,15) and write a program for the Selection sort.
15. How many number of iterations will be taken to search key=12 for the given list of numbers (
10,2,4,8,5,12,11) using Linear search and Binary search. Explain step by step.

ALL LAB PROGRAMS OF UNIT-2

Unit-3 : Stacks and Queues

2M Questions

1. Write 4 applications of Priority Queues.


2. Write few applications of dequeue.
3. Define Stack
4. Define Queue
5. Define dequeue
6. Define Priority Queue.
7. Write 4 applications of Queues.
8. Write 4 applications of Stacks.
9. What are the different ways to implement stack.
10. Mention the advantages of representing stacks using linked lists than arrays
11. What is Queue. List different types of queues.
12. List out the functions of stack.
13. List out the functions of Queues.
14. Differentiate between Queue and Priority Queue.
15. Differentiate between stacks and Queues.

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.

ALL LAB PROGRAMS OF UNIT-3


n = len(lst)
for i in range(n-1): # no. of iterations
for j in range(0, n-i-1):
if lst[j] > lst[j+1]:
# excahnge values
temp = lst[j]
lst[j] = lst[j+1]
lst[j+1] = temp
return lst
l = [ 9,3,7,12,8,11,15]
bubble_sort(l)
output:
[3, 7, 8, 9, 11, 12, 15]
program for the Selection sort.
def select_sort(lst):
n = len(lst)
for i in range(n-1):
for j in range(i+1,n):
if lst[i] > lst[j]:
# excahnge values
temp = lst[i]
lst[i] = lst[j]
lst[j] = temp
return lst

15. How many number of iterations will be taken to search key=12


for the given list of numbers ( 10,2,4,8,5,12,11) using Linear search
and Binary search. Explain step by step.
A)

Unit-3 : Stacks and Queues

2M Questions

1. Write 4 applications of Priority Queues.


A)
 Breadth First Search or BFS for a Graph.
 Level Order Binary Tree Traversal.
 Queue using Stacks.
 Queue Interface In Java.
2. Write few applications of dequeue.
A)
An internet browser's history.Another common application of the deque is
storing a computer code application's list of undo operations. Have you
ever see Money-Control App, it'll show the stocks you last visited, it'll take
away the stocks when a while and can add the most recent ones.

The A-steal algorithm implements task scheduling for multiple processors


(multiprocessor scheduling). - The processor gets the first element from
the double ended queue. - When one of the processors completes
execution of its own thread, it can steal a thread from other processors.

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.

6. Define Priority Queue.


A)
The priority queue in the data structure is an extension of the “normal”
queue. It is an abstract data type that contains a group of items. It is like
the “normal” queue except that the dequeuing elements follow a priority
order. The priority order dequeues those items first that have the highest
priority.

7. Write 4 applications of Queues.


A)
 The queue is used when things don't have to be processed
immediately, but have to be processed in First In First Out order like
Breadth First Search.
 Queues are flexible, requiring no communications programming. The
programmer does not need any knowledge of inter-process
communication.
 The queue can remain active when there are no entries, ready to
process data entries when necessary.
 Call Center phone systems uses Queues to hold people calling them in
an order, until a service representative is free.

8. Write 4 applications of Stacks.


A)
 Expression Handling − Infix to Postfix or Infix to Prefix Conversion
 Backtracking Procedure − Backtracking is one of the algorithm
designing technique.
 Another great use of stack is during the function call and return
process.Stacks can be used to check parenthesis matching in an
expression.

9. What are the different ways to implement stack.


A)
 Implementation using list
 Implementation using collections.deque
 Implementation Using queue module

10. Mention the advantages of representing stacks using linked


lists than arrays
A)
Linked List and Arrays are both used for storage of elements, but both are
different techniques. In an array, elements are one after the
another(successive memory allocation). But in linked list, memory is not
contiguous.

Advantages :

 Size is not an issue as compared to arrays.

 Addition/Deletion of an element from the list at any index which is an


O(1) operation in Lists as compared to Arrays.

 They can be used as underlying dat


 Dynamic size As the size of linked list is not fixed so we can add or
remove as much elements as required. But in array we have to pre-
define the array size which we can’t change later.

 Ease of insertion/deletion

11. What is Queue. List different types of queues.


A)
A queue is a useful data structure in programming. It is similar to the ticket
queue outside a cinema hall, where the first person entering the queue is
the first person who gets the ticket.
There are four different types of queues:
● Simple Queue
● Circular Queue
● Priority Queue
● Double Ended Queue

12. List out the functions of stack.


A)
The functions associated with stack are:
 empty() – Returns whether the stack is empty – Time Complexity :
O(1)
 size() – Returns the size of the stack – Time Complexity : O(1)
 top() – Returns a reference to the top most element of the stack –
Time Complexity : O(1)
 push(g) – Adds the element ‘g’ at the top of the stack – Time
Complexity : O(1)
 pop() – Deletes the top most element of the stack – Time Complexity :
O(1)

13. List out the functions of Queues.


A)
Queue is an abstract data structure, somewhat similar to Stacks. Unlike
stacks, a queue is open at both its ends. One end is always used to insert
data (enqueue) and the other is used to remove data (dequeue). Queue
follows First-In-First-Out methodology, i.e., the data item stored first will be
accessed first.

14. Differentiate between Queue and Priority Queue.


A)
Queue is a list where insertion is done at one end and removal is done at
the other end.

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

2. Different types of queue? list applications of queues.


A)

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:

Its applications are process scheduling, disk scheduling, memory


management, IO buffer, pipes, call center phone systems, and interrupt
handling.

Circular Queue

A circular queue permits better memory utilization than a simple


queue when the queue has a fixed size.
In this queue, the last node points to the first node and creates a circular
connection. Thus, it allows us to insert an item at the first node of the
queue when the last node is full and the first node is free.
It’s also called a ring buffer:

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 priority queue is a special kind of queue in which each item has a


predefined priority of service. In this queue, the enqueue operation
takes place at the rear in the order of arrival of the items, while the
dequeue operation takes place at the front based on the priority of the
items.
That is to say that an item with a high priority will be dequeued before
an item with a low priority.
In the case, when two or more items have the same priority, then they’ll be
dequeued in the order of their arrival. Hence, it may or may not strictly
follow the FIFO rule:

It’s used in interrupt handling, Prim’s algorithm, Dijkstra’s algorithm, A*


search algorithm, heap sort, and Huffman code generation.

Double-Ended Queue (Deque)

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:

It’s used to save browsing history, perform undo operations, implement A-


Steal job scheduling algorithm, or implement a stack or implement a
simple queue.
Further, it has two special cases: input-restricted deque and output-
restricted deque.
In the first case, the enqueue operation takes place only at the rear, but
the dequeue operation takes place at both rear and front:
An input-restricted queue is useful when we need to remove an item from
the rear of the queue.
In the second case, the enqueue operation takes place at both rear and
front, but the dequeue operation takes place only at the front:

An output-restricted queue is handy when we need to insert an item at the


front of the queue.

3. Mention different ways to implement stack data structure. Write


sample code for each method.
A)
There are two ways to implement a stack:
 Using array
 Using linked list

Using array

from sys import maxsize

# Function to create a stack. It initializes size of stack as 0

def createStack():

stack = []

return stack
# Stack is empty when stack size is 0

def isEmpty(stack):

return len(stack) == 0

# Function to add an item to stack. It increases size by 1

def push(stack, item):

stack.append(item)

print(item + " pushed to stack ")

# Function to remove an item from stack. It decreases size by 1

def pop(stack):

if (isEmpty(stack)):

return str(-maxsize -1) # return minus infinite

return stack.pop()

# Function to return the top from stack without removing it

def peek(stack):

if (isEmpty(stack)):

return str(-maxsize -1) # return minus infinite

return stack[len(stack) - 1]

# Driver program to test above functions

stack = createStack()

push(stack, str(10))

push(stack, str(20))
push(stack, str(30))

print(pop(stack) + " popped from stack")

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

Using Linked list

class StackNode:

# Constructor to initialize a node

def __init__(self, data):

self.data = data

self.next = None

class Stack

# Constructor to initialize the root of linked list

def __init__(self):

self.root = None

def isEmpty(self):

return True if self.root is None else False

def push(self, data):


newNode = StackNode(data)

newNode.next = self.root

self.root = newNode

print "% d pushed to stack" % (data)

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)

print "% d popped from stack" % (stack.pop())


print "Top element is % d " % (stack.peek())

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

4. Implement queue using stack.


A)
Method 1 (By making enQueue operation costly) This method makes
sure that oldest entered element is always at the top of stack 1, so that
deQueue operation just pops from stack1. To put the element at top of
stack1, stack2 is used.
enQueue(q, x):

class Queue:

def __init__(self):

self.s1 = [ ]

self.s2 = [ ]

def enQueue(self, x):

# Move all elements from s1 to s2

while len(self.s1) != 0:

self.s2.append(self.s1[-1])

self.s1.pop()
# Push item into self.s1

self.s1.append(x)

# Push everything back to s1

while len(self.s2) != 0:

self.s1.append(self.s2[-1])

self.s2.pop()

# Dequeue an item from the queue

def deQueue(self)

# if first stack is empty

if len(self.s1) == 0:

print("Q is Empty")

# Return top of self.s1

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())

# This code is contributed by PranchalK

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 = [ ]

# EnQueue item to the queue

def enQueue(self, x):

self.s1.append(x)

# DeQueue item from the queue


def deQueue(self):

# if both the stacks are empty

if len(self.s1) == 0 and len(self.s2) == 0:

print("Q is Empty")

return

# if s2 is empty and s1 has elements

elif len(self.s2) == 0 and len(self.s1) > 0:

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

5. Implement Queue using Linked lists in Python.


A)

# Python3 program to demonstrate linked list

# based implementation of queue

# A linked list (LL) node

# to store a queue entry

Class Node:

def __init__(self, data):

self.data = data

self.next = None

# A class to represent a queue

# The queue, front stores the front node

# of LL and rear stores the last node of LL

class Queue:

def __init__(self):

self.front = self.rear = None


def isEmpty(self):

return self.front == None

# Method to add an item to the queue

def EnQueue(self, item):

temp = Node(item)

if self.rear == None:

self.front = self.rear = temp

return

self.rear.next = temp

self.rear = temp

# Method to remove an item from queue

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()

print("Queue Front " + str(q.front.data))

print("Queue Rear " + str(q.rear.data))

Output:
Queue Front : 40
Queue Rear : 50

6. Differentiate between Queue, Priority Queue and Deque.


A)
Deque: Deque is a sequence container with the ability of expansion
and contraction on both ends. It is a template of Standard Template
Library or STL in C++is. It is similar to vectors but are more efficient
for the insertion and deletion of elements. Contiguous storage
allocation in deque may not be guaranteed as in vectors.
Queue: A Queue is a linear data structure that follows a First In First Out
(FIFO) order in which the operations are performed. It is a type of
container adaptor where elements are inserted into one end of the
container and deleted from the other.

Priority Queue is an extension of queue with following properties.


1. Every item has a priority associated with it.
2. An element with high priority is dequeued before an element with
low priority.
3. If two elements have the same priority, they are served
according to their order in the queue.

7. Implement Stack using Linked list in Python.


A) class Node:

# Class to create nodes of linked list


# constructor initializes node automatically
def __init__(self,data):
self.data = data
self.next = None

class Stack:

# head is default NULL


def __init__(self):
self.head = None
# Checks if stack is empty
def isempty(self):
if self.head == None:
return True
else:
return False

# Method to add data to the stack


# adds to the start of the stack
def push(self,data):

if self.head == None:
self.head=Node(data)

else:
newnode = Node(data)
newnode.next = self.head
self.head = newnode

# Remove element that is the current head (start of the stack)


def pop(self):

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

# Returns the head node data


def peek(self):

if self.isempty():
return None

else:
return self.head.data

# Prints out the stack


def display(self):

iternode = self.head
if self.isempty():
print("Stack Underflow")

else:

while(iternode != None):

print(iternode.data,"->",end = " ")


iternode = iternode.next
return

# Driver code
MyStack = Stack()

MyStack.push(11)
MyStack.push(22)
MyStack.push(33)
MyStack.push(44)

# Display stack elements


MyStack.display()

# Print top element of stack


print("\nTop element is ",MyStack.peek())

# Delete top elements of stack


MyStack.pop()
MyStack.pop()

# Display stack elements


MyStack.display()

# Print top element of stack


print("\nTop element is ", MyStack.peek())

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

# Python code to demonstrate deque

from collections import deque

# 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

# Python code to demonstrate working of

# append(), appendleft(), pop(), and popleft()

# importing "collections" for deque operations


import collections

# initializing deque

de = collections.deque([1,2,3])

# using append() to insert element at right end

# inserts 4 at the end of deque

de.append(4)

# printing modified deque

print ("The deque after appending at right is : ")

print (de)

# using appendleft() to insert element at left end

# inserts 6 at the beginning of deque

de.appendleft(6)

# printing modified deque

print ("The deque after appending at left is : ")

print (de)

# using pop() to delete element from right end

# deletes 4 from the right end of deque

de.pop()

# printing modified deque

print ("The deque after deleting from right is : ")


print (de)

# using popleft() to delete element from left end

# deletes 6 from the left end of deque

de.popleft()

# printing modified deque

print ("The deque after deleting from left is : ")

print (de)

Output:

The deque after appending at right is :


deque([1, 2, 3, 4])
The deque after appending at left is :
deque([6, 1, 2, 3, 4])
The deque after deleting from right is :
deque([6, 1, 2, 3])
The deque after deleting from left is :
deque([1, 2, 3])
 index(ele, beg, end) :- This function returns the first index of
the value mentioned in arguments, starting searching from
beg till end index.
 insert(i, a) :- This function inserts the value mentioned in
arguments(a) at index(i) specified in arguments.
 remove() :- This function removes the first occurrence of
value mentioned in arguments.
 count() :- This function counts the number of occurrences of
value mentioned in arguments.
 Python3
# Python code to demonstrate working of

# insert(), index(), remove(), count()

# importing "collections" for deque operations

import collections

# initializing deque

de = collections.deque([1, 2, 3, 3, 4, 2, 4])

# using index() to print the first occurrence of 4

print ("The number 4 first occurs at a position : ")

print (de.index(4,2,5))

# using insert() to insert the value 3 at 5th position

de.insert(4,3)

# printing modified deque

print ("The deque after inserting 3 at 5th position is : ")

print (de)

# using count() to count the occurrences of 3

print ("The count of 3 in deque is : ")

print (de.count(3))

# using remove() to remove the first occurrence of 3

de.remove(3)
# printing modified deque

print ("The deque after deleting first occurrence of 3 is : ")

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.

 extendleft(iterable) :- This function is used to add multiple


values at the left end of deque. The argument passed is an
iterable. Order is reversed as a result of left appends.

 reverse() :- This function is used to reverse order of deque


elements.

 rotate() :- This function rotates the deque by the number


specified in arguments. If the number specified is negative,
rotation occurs to left. Else rotation is to right.
 Python3

# Python code to demonstrate working of

# extend(), extendleft(), rotate(), reverse()

# importing "collections" for deque operations

import collections
# initializing deque

de = collections.deque([1, 2, 3,])

# using extend() to add numbers to right end

# adds 4,5,6 to right end

de.extend([4,5,6])

# printing modified deque

print ("The deque after extending deque at end is : ")

print (de)

# using extendleft() to add numbers to left end

# adds 7,8,9 to right end

de.extendleft([7,8,9])

# printing modified deque

print ("The deque after extending deque at beginning is : ")

print (de)

# using rotate() to rotate the deque

# rotates by 3 to left

de.rotate(-3)

# printing modified deque

print ("The deque after rotating deque is : ")

print (de)
# using reverse() to reverse the deque

de.reverse()

# printing modified deque

print ("The deque after reversing deque is : ")

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)

9. Implement priority and double ended queue in python


A)

Implement priority

# A simple implementation of Priority Queue

# using Queue.

class PriorityQueue(object):

def __init__(self):

self.queue = []
def __str__(self):

return ' '.join([str(i) for i in self.queue])

# for checking if the queue is empty

def isEmpty(self):

return len(self.queue) == 0

# for inserting an element in the queue

def insert(self, data):

self.queue.append(data)

# for popping an element based on Priority

def delete(self):

try:

max = 0

for i in range(len(self.queue)):

if self.queue[i] > self.queue[max]:

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)

while not myQueue.isEmpty():

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

def insert_start(self, data):


if self.count == 0:
self.queue = [data,]
self.count = 1
return

self.queue.insert(0, data)
self.count += 1
return

def insert_end(self, data):


if self.count == 0:
self.queue = [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

def get(self, index):


if index >= self.count | index < 0:
raise ValueError("Index out of range.")

return self.queue[index]

def size(self):
return self.count

def display(self):
print(self)
return

10. Convert following expression X+(Y * Z) – ((N * M +O) /Q) in to


post fix form.
A)

11. Differences between stacks and queues.


A)
Stacks Queues

Stacks are based on the LIFO


principle, i.e., the element Queues are based on the FIFO principle, i.e.,
inserted at the last, is the first the element inserted at the first, is the first
element to come out of the list. element to come out of the list.

Insertion and deletion in queues takes place


Insertion and deletion in stacks from the opposite ends of the list. The insertion
takes place only from one end takes place at the rear of the list and the
of the list called the top. deletion takes place from the front of the list.

Insert operation is called push


operation. Insert operation is called enqueue operation.

Delete operation is called pop


operation. Delete operation is called dequeue operation.

In stacks we maintain only one In queues we maintain two pointers to access


pointer to access the list, called the list. The front pointer always points to the
the top, which always points to first element inserted in the list and is still
the last element present in the present, and the rear pointer always points to
list. the last inserted element.

Stack is used in solving Queue is used in solving problems having


problems works on recursion. sequential processing.

You might also like