0% found this document useful (0 votes)
27 views24 pages

Data Structures

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)
27 views24 pages

Data Structures

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/ 24

DATA STRUCTURES

Fill in the Blanks


1. Data Structure means organization of data.
2. A data structure has well defined operations, behaviour and properties.
3. A stack is a linear list, also known as LIFO list.
4. A list is a mutable sequence of data elements indexed by their position.
5. Traversing means accessing or visiting or processing each element of any data structure.
6. push is the term coined for insertion of elements in a Stack list.
7. Consider the following operations done on Stack:
push(5)
push(8)
pop()
push(2)
push(5)
pop()
pop()
pop()
push(1)
pop()
The output of the above snippet is [], empty list.
8. In the Stack, if a user tries to remove an element from the empty Stack, it is called underflow of
stack.
9. If the elements "A", "B", "C" and "D" are placed in a queue and are deleted one at a time, the
order in which they will be removed will be A, B, C and D.
10. The process of inserting an element in a queue is called enqueue while deleting an element from
a queue is called dequeue.

State True or False


1.Single-ended linear structure is a type of queue data structure.
Answer
False
Reason — A single-ended linear structure is a type of stack data structure because a stack is a
linear/sequence structure or a list of elements where insertion and deletion can only occur at one
end, following the Last-In-First-Out (LIFO) principle.
2.Reversing a word/line is an application of Stack.
Answer
True
Reason — Reversing a word or a line is an application of the stack data structure. This can be
accomplished by pushing each character onto a stack as it is read. When the line is finished,
characters are popped off the stack, and they will come off in reverse order.
3.The insertion and deletion from a Stack takes place only from the 'TOP'.
Answer
True
Reason — A stack is a linear/sequence structure or a list of elements in which insertion and deletion
can take place only at one end, i.e., stack's top.
4.A queue behaves on the basis of LIFO principle.
Answer
False
Reason — A stack behaves based on the Last-In-First-Out (LIFO) principle, meaning that the last
element added to the stack is the first one to be removed, while a queue operates according to the
First-In-First-Out (FIFO) principle, allowing insertions only at the rear end and deletions only at the
front end.
5.When a queue is implemented with the help of a list, it is termed as a linear queue.
Answer
True
Reason — When a queue is implemented using a list, it is referred to as a linear queue. The syntax is
: Queue = list() or Queue = [].
6.Deletion of an element from the queue is termed as pop operation.
Answer
False
Reason — The deletion of an element from the stack is termed as a pop operation, while the
deletion of an element from the queue is termed as dequeue.
7.An element to a queue is added from the front end.
Answer
False
Reason — An element is added to a queue from the rear end, while an element is deleted from the
front end of the queue.
8.Handling the processes of a network printer is the most important application of queues.
Answer
True
Reason — Queues are very useful in a multi-user environment, such as in the case of a network
printer, where multiple requests for print operations are generated by several users on the network.
If the printer is busy, successive print requests are spooled to the hard disk, where they wait in a
queue until the printer becomes available. Hence, handling the processes of a network printer is one
of the most important applications of queues.
9.The append() function inserts an element at the rear end in a queue.
Answer
True
Reason — The built-in list function "append()" inserts an element at the rear end of a queue.
10.Stack is a linear data structure.
Answer
True
Reason — A stack is a linear data structure following the Last In, First Out (LIFO) principle, where
elements are arranged sequentially.
11.PUSH operation may result in underflow condition.
Answer
False
Reason — When attempting to remove an element (POP operation) from an empty stack, it leads to
an underflow condition, resulting in an exception being raised.

Multiple Choice s
1.The process of inserting an element in Stack is called:
1. Create
2. Push
3. Evaluation
4. Pop
Answer
Push
Reason — The process of inserting/adding a new element to the Stack is called PUSH operation.
2.The process of removing an element from Stack is called:
1. Create
2. Push
3. Evaluation
4. Pop
Answer
Pop
Reason — The process of removing/deleting an element from Stack is called Pop operation.
3.In a Stack, if a user tries to remove an element from an empty Stack, the situation is called:
1. Underflow
2. Empty collection
3. Overflow
4. Garbage collection
Answer
Underflow
Reason — In a stack, if a user attempts to remove an element from an empty stack, the situation is
called "underflow". This occurs because there are no elements left in the stack to be removed.
4.Pushing an element into a Stack already having five elements and a Stack of size 5, then the Stack
becomes:
1. User flow
2. Crash
3. Underflow
4. Overflow
Answer
Overflow
Reason — When pushing an element into a stack that already has five elements and the stack size is
limited to 5, the situation is called an "overflow." This is because the stack has reached its maximum
capacity, and adding another element would exceed the stack's limit, resulting in an overflow
condition.
5.Entries in a Stack are "ordered". What is the meaning of this statement?
1. A collection of Stacks can be sorted.
2. Stack entries may be compared with the '<' operation.
3. The entries are stored in a linked list.
4. There is a Sequential entry that is one by one.
Answer
There is a Sequential entry that is one by one.
Reason — The statement "Entries in a Stack are ordered" means that the entries in a stack are
arranged in a sequential order, where each new entry is placed on top of the previous entry. This
sequential arrangement follows the Last-In-First-Out (LIFO) principle.
6.Which of the following applications may use a Stack?
1. A parentheses balancing program
2. Tracking of local variables at run time
3. Compiler Syntax Analyzer
4. All of these
Answer
All of these
Reason — Stacks, with their last-in-first-out (LIFO) functionality, are important in parentheses
balancing programs, tracking local variables at runtime for efficient memory management, and
compiler syntax analyzers for parsing expressions and managing program flow.
7.Consider the usual algorithm for determining whether a sequence of parentheses is balanced.
The maximum number of parentheses that appear on the Stack AT ANY ONE TIME when the
algorithm analyzes: (()(())(())) is:
1. 1
2. 2
3. 3
4. 4 or more
Answer
3.Reason — Initially, two opening parentheses '(' are pushed onto the stack. When a closing
parenthesis ')' is encountered, it is matched with an open parenthesis on the stack. Subsequently,
two new opening parentheses are pushed onto the stack. Then subsequent two closing parentheses
are matched with open parentheses on the stack and this process repeats. ensuring that at most, 3
parentheses are on the stack at any given time, maintaining balance.
8.A linear list of elements in which deletion can be done from one end (front) and insertion can take
place only at the other end (rear) is known as a:
1. Queue
2. Stack
3. Tree
4. Linked list
Answer
Queue
Reason — A queue is represented as a linear list where insertion (enqueue) can be performed at one
end (rear) and deletion (dequeue) can be performed at the other end (front). This characteristic of
queues follows the First-In-First-Out (FIFO) principle.
9.A Queue is a:
1. FIFO (First In First Out) list
2. LIFO (Last In First Out) list
3. Ordered array
4. Linear tree
Answer
FIFO (First In First Out) list
Reason — A Queue is a FIFO (First In First Out) list, meaning that the item that is first inserted into
the queue is also the first one to be removed.

Assertions and Reasons


1.Assertion (A): The major implementation of using a data structure is to manage the storage of
data in the memory efficiently.
Reasoning (R): Data structure refers to the way memory is allocated for holding data using minimum
space. It leads to faster data access during the execution of the program.
1. Both A and R are true and R is the correct explanation of A.
2. Both A and R are true but R is not the correct explanation of A.
3. A is true but R is false.
4. A is false but R is true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
Data structures play a crucial role in efficiently managing data in memory. A data structure refers to
the method of allocating memory to hold data using minimal space, which ensures faster data access
during program execution.
2.Assertion (A): While working with Stacks, the program should check for Overflow condition before
executing push operation and, similarly, check for Underflow before executing pop operation.
Reasoning (R): In Stack, Underflow means there is no element available to remove and Overflow
means no further element can be added to it.
1. Both A and R are true and R is the correct explanation of A.
2. Both A and R are true but R is not the correct explanation of A.
3. A is true but R is false.
4. A is false but R is true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
To use a Stack efficiently, it's crucial to check its status by examining overflow conditions before
executing a push operation and underflow conditions before executing a pop operation. In a stack,
underflow occurs when there are no elements available to remove (e.g., trying to pop from an empty
stack), while overflow happens when there's no more space to add elements (e.g., trying to push
onto a full stack).
3.Assertion (A): Stack is a memory structure that works on the principle of FIFO (First In, First Out).
Reasoning (R): Stack is implemented using list and allows to add an element using append() method.
1. Both A and R are true and R is the correct explanation of A.
2. Both A and R are true but R is not the correct explanation of A.
3. A is true but R is false.
4. A is false but R is true.
Answer
A is false but R is true.
Explanation
A stack is a memory structure that works on the principle of LIFO (Last In, First Out), meaning that
the last element added to the stack is the first one to be removed. In Python, a stack can be
implemented using a list data structure, and the "append()" method is used to add elements to the
top of the stack.
4.Assertion (A): A Stack is a linear data structure that stores the elements in First In, First Out order.
Reasoning (R): In Stack, a new element is added and removed from one end only.
1. Both A and R are true and R is the correct explanation of A.
2. Both A and R are true but R is not the correct explanation of A.
3. A is true but R is false.
4. A is false but R is true.
Answer
A is false but R is true.
Explanation
A stack is a linear data structure that stores elements in LIFO (Last In, First Out) order, where the last
element added to the stack is the first one to be removed. In a stack, a new element is added and
removed from only one end, which is the top of the stack.
5.Assertion (A): Stack and Queue are linear data structures.
Reasoning (R): List, tuples and dictionaries are Python built-in linear data structures.
1. Both A and R are true and R is the correct explanation of A.
2. Both A and R are true but R is not the correct explanation of A.
3. A is true but R is false.
4. A is false but R is true.
Answer
A is true but R is false.
Explanation
Stacks and queues are linear data structures because they organize data elements in a linear order,
allowing elements to be accessed in a sequential manner. Python provides built-in data structures
like lists, tuples, and dictionaries. Lists and tuples are examples of linear data structures as they store
elements in a specific linear order, while dictionaries are non-linear data structures because they do
not maintain a specific linear order, and elements are accessed based on their keys rather than
indices.
6.Assertion (A): An element in a Stack is removed from its Top.
Reasoning (R): The process of removing an element from a Stack is called pop.
1. Both A and R are true and R is the correct explanation of A.
2. Both A and R are true but R is not the correct explanation of A.
3. A is true but R is false.
4. A is false but R is true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
An element in a stack is removed from its top. The stack follows the Last-In-First-Out (LIFO) approach,
where the last element added (the top element) is the first one to be removed. The process of
removing an element from a stack is called pop.
7.Assertion (A): An error gets displayed when you try to delete an element from an empty Stack.
Reasoning (R): Inserting an element when the Stack is full is termed as Underflow.
1. Both A and R are true and R is the correct explanation of A.
2. Both A and R are true but R is not the correct explanation of A.
3. A is true but R is false.
4. A is false but R is true.
Answer
A is true but R is false.
Explanation
When we attempt to delete an element from an empty stack, it results in an error known as an
underflow error. This occurs because the stack is empty, and there's no element to remove. On the
other hand, inserting an element when the stack is full is termed as an overflow condition.

Solutions to Unsolved:
1.What is Stack? Why is it called LIFO data structure?
Answer
A stack is a linear/sequence structure or a list of elements in which insertion and deletion can take
place only at one end, i.e., Stack's top. Because of this, Stack is called LIFO data structure. The Last-
In-First-Out (LIFO) means the element inserted last would be the first to be deleted or accessed from
the stack.
2.List two ways to implement Stack.
Answer
The two ways to implement Stack are as follows :
1. Stack = list()
2. Stack = []
3.Write applications of Stack.
Answer
The applications of Stack include:
1. Reversing a Word/Line — This can be accomplished by pushing each character on to a Stack
as it is read. When the line is finished, characters are popped off the Stack and they will
come off in the reverse order.
2. Evaluation of Arithmetic Expressions — Stack is used to evaluate these arithmetic
expressions on the basis of operator precedence.
3. Processing Function Calls — The compilers use Stacks to store the previous state of a
program when a function is called or during recursion.
4. Backtracking — Backtracking is a form of recursion which involves choosing only one option
out of the possibilities. Backtracking is used in a large number of puzzles like Sudoku and in
optimization problems such as Knapsack.
5. Undo Mechanism in Text Editors — This operation is accomplished by keeping all text
changes in a Stack.
4.Can a Stack be used to convert a decimal number into a binary number?
Answer
Yes, a Stack can be used to convert a decimal number into a binary number.
5.Write an algorithm to push an element into the Stack.
Answer
An algorithm to push an element into the Stack is as follows:
1. START
2. Stack = list() or Stack = [] #Initialize a Stack using list
3. element = input("Enter the value to be added in the stack:")
4. Stack.append(element) #Adding element into list
5. END
6.Write an algorithm to pop an element from the Stack.
Answer
An algorithm to pop an element from the Stack is as follows:
1. START
2. St_len = len(Stack) #Count the total number of elements in the Stack and checks whether the
Stack is empty or not
3. if St_len == []: or if not Stack: or If not len(Stack):
print("Stack is empty")
go to step 6
4. element = Stack.pop() #Removing last element from top of the Stack
5. print(element)
6. END
7.Write an interactive menu-driven program implementing Stack using list. The list is storing numeric
data.
Solution
def push(num):
h = int(input("Enter a number: "))
num.append(h)

def pop(num):
if len(num) == 0:
print("No number to delete")
else:
print("Deleted number is:", num.pop())

def display(num):
print(num)

num = []
while True:
print("1. Add number")
print("2. Delete number")
print("3. Display numbers")
print("4. Exit")
op = int(input("Enter the Choice: "))
if op == 1:
push(num)
elif op == 2:
pop(num)
elif op == 3:
display(num)
elif op == 4:
print("Exiting program.")
break
else:
print("Invalid choice. Please enter a number between 1 and 4.")
Output
Explain
1. Add number
2. Delete number
3. Display numbers
4. Exit
Enter the Choice: 1
Enter a number: 2
1. Add number
2. Delete number
3. Display numbers
4. Exit
Enter the Choice: 1
Enter a number: 4
1. Add number
2. Delete number
3. Display numbers
4. Exit
Enter the Choice: 1
Enter a number: 6
1. Add number
2. Delete number
3. Display numbers
4. Exit
Enter the Choice: 1
Enter a number: 8
1. Add number
2. Delete number
3. Display numbers
4. Exit
Enter the Choice: 3
[2, 4, 6, 8]
1. Add number
2. Delete number
3. Display numbers
4. Exit
Enter the Choice: 2
Deleted number is: 8
1. Add number
2. Delete number
3. Display numbers
4. Exit
Enter the Choice: 3
[2, 4, 6]
1. Add number
2. Delete number
3. Display numbers
4. Exit
Enter the Choice: 4
Exiting program.
8.Write an interactive menu-driven program to implement Stack using list. The list contains the
names of students.
Solution
def push(student):
h = input("Enter a name: ")
student.append(h)

def pop(student):
if len(student) == 0:
print("No name to delete")
else:
print("Deleted name is:", student.pop())

def display(student):
print(student)

student = []
while True:
print("1. Add name")
print("2. Delete name")
print("3. Display names")
print("4. Exit")
op = int(input("Enter the Choice: "))
if op == 1:
push(student)
elif op == 2:
pop(student)
elif op == 3:
display(student)
elif op == 4:
print("Exiting program.")
break
else:
print("Invalid choice. Please enter a number between 1 and 4.")
Output
Explain
1. Add name
2. Delete name
3. Display names
4. Exit
Enter the Choice: 1
Enter a name: Prajwal
1. Add name
2. Delete name
3. Display names
4. Exit
Enter the Choice: 1
Enter a name: Amrita
1. Add name
2. Delete name
3. Display names
4. Exit
Enter the Choice: 1
Enter a name: Kavya
1. Add name
2. Delete name
3. Display names
4. Exit
Enter the Choice: 1
Enter a name: Drishti
1. Add name
2. Delete name
3. Display names
4. Exit
Enter the Choice: 3
['Prajwal', 'Amrita', 'Kavya', 'Drishti']
1. Add name
2. Delete name
3. Display names
4. Exit
Enter the Choice: 2
Deleted name is: Drishti
1. Add name
2. Delete name
3. Display names
4. Exit
Enter the Choice: 3
['Prajwal', 'Amrita', 'Kavya']
1. Add name
2. Delete name
3. Display names
4. Exit
Enter the Choice: 4
Exiting program.
9.How does FIFO describe queue?
Answer
FIFO, First In First Out, defines a queue because in a queue, elements are retrieved from one end
(called the front end) and inserted at another end (rear end). Thus, at any time, in a queue, retrieval
gets the oldest element, while always adding to the rear of the queue. Thus, items are processed in
first-in, first-out (FIFO) order.
10.Write a menu-driven Python program using queue to implement movement of shuttlecock in its
box.
Solution
queue = []

def display_queue():
if not queue:
print("Queue is empty")
else:
print("Current queue:", queue)

def enqueue(item):
queue.append(item)

def dequeue():
if queue:
removed = queue.pop(0)
print("Removed", removed, "from the queue")
else:
print("Queue is empty, cannot remove")

while True:
print("\nMENU:")
print("1. Add movement to the queue")
print("2. Remove movement from the queue")
print("3. Display current queue")
print("4. Exit")

choice = input("Enter your choice (1-4): ")

if choice == '1':
movement = input("Enter the movement (up/down): ")
enqueue(movement)
print("Added", movement, "to the queue")
elif choice == '2':
dequeue()
elif choice == '3':
display_queue()
elif choice == '4':
print("Exiting program...")
break
else:
print("Invalid choice, please try again")
Output
Explain

MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 1
Enter the movement (up/down): up
Added up to the queue

MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 1
Enter the movement (up/down): down
Added down to the queue

MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 3
Current queue: ['up', 'down']

MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 2
Removed up from the queue

MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 3
Current queue: ['down']

MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 4
Exiting program...
11.Give the necessary declaration of a list implemented Stack containing float type numbers. Also,
write a user-defined function to pop a number from this Stack.
Solution
# Declaration for list implemented stack
Stack = list()
#Function body to pop a number from the stack
def pop_element(Stack):
if not Stack:
print("Stack is empty")
else:
Num = Stack.pop()
print("Value deleted from stack is", Num)

Stack = [1.5, 2.7, 3.2, 4.9]


print("Initial Stack:", Stack)

pop_element(Stack)
print("Stack after pop operation:", Stack)
Output
Initial Stack: [1.5, 2.7, 3.2, 4.9]
Value deleted from stack is 4.9
Stack after pop operation: [1.5, 2.7, 3.2]
12.A linear Stack called Directory contains the following information as contacts:
— Pin code of city
— Name of city
Write add(Directory) and delete(Directory) methods in Python to add and remove contacts using
append() and pop() operations in Stack.
Solution
def add(Directory):
pincode = int(input("Enter pincode of city: "))
cityname = input("Enter the city name: ")
contact = [pincode, cityname]
Directory.append(contact)

def delete(Directory):
if (Directory == []):
print("Directory is empty")
else:
print("Deleted contact:", Directory.pop())

Directory = []
add(Directory)
add(Directory)
print("Initial Directory Stack:", Directory)

delete(Directory)
print("Directory Stack after deletion:", Directory)
Output
Explain
Enter pincode of city: 586789
Enter the city name: Bangalore
Enter pincode of city: 567890
Enter the city name: Mysore
Initial Directory Stack: [[586789, 'Bangalore'], [567890, 'Mysore']]
Deleted contact: [567890, 'Mysore']
Directory Stack after deletion: [[586789, 'Bangalore']]
13.Write add(Books) and delete(Books) methods in Python to add Books and Remove Books
considering them to act as append() and pop() operations in Stack.
Solution
def add(Books):
bookname = input("Enter the book name: ")
Books.append(bookname)

def delete(Books):
if Books == []:
print("Books is empty")
else:
print("Deleted Book", Books.pop())

Books = []

add(Books)
add(Books)
add(Books)
print("Initial Books Stack:", Books)

delete(Books)
print("Books Stack after deletion:", Books)
Output
Explain
Enter the book name: Three thousand stitches
Enter the book name: Wings of fire
Enter the book name: Ignited minds
Initial Books Stack: ['Three thousand stitches', 'Wings of fire', 'Ignited minds']
Deleted Book Ignited minds
Books Stack after deletion: ['Three thousand stitches', 'Wings of fire']
14.Write AddClient(Client) and DeleteClient(Client) methods in Python to add a new client and
delete a client from a list client name, considering them to act as insert and delete operations of the
Queue data structure.
Solution
def AddClient(client):
client_name = input("Enter client name: ")
client.append(client_name)

def DeleteClient(client):
if client == []:
print("Queue is empty")
else:
print("Deleted client:", client.pop(0))

client = []

AddClient(client)
AddClient(client)
AddClient(client)
print("Initial Client Queue:", client)

DeleteClient(client)
print("Client Queue after deletion:", client)
Output
Explain
Enter client name: Rahul
Enter client name: Tanvi
Enter client name: Vidya
Initial Client Queue: ['Rahul', 'Tanvi', 'Vidya']
Deleted client: Rahul
Client Queue after deletion: ['Tanvi', 'Vidya']
15.Write Addscore(Game) and Delscore(Game) methods in Python to add new Score in the list of
score in a game and remove a score from a list of score of a game considering these methods to act
as PUSH and POP operation of data structure Stack.
Solution
def Addscore(Game):
score = int(input("Enter the score to add: "))
Game.append(score)

def Delscore(Game):
if Game == []:
print("Game's score list is empty")
else:
print("Deleted score:", Game.pop())

Game = []

Addscore(Game)
Addscore(Game)
Addscore(Game)
print("Initial Game Stack:", Game)

Delscore(Game)
print("Game Stack after deletion:", Game)
Output
Explain
Enter the score to add: 10
Enter the score to add: 15
Enter the score to add: 20
Initial Game Stack: [10, 15, 20]
Deleted score: 20
Game Stack after deletion: [10, 15]
16.Write a Python program to sort a Stack in ascending order without using an additional Stack.
Solution
def pushSorted(s, num):
if len(s) == 0 or num > s[-1]:
s.append(num)
return
else:
t = s.pop()
pushSorted(s, num)
s.append(t)

def doSort(s):
if len(s) != 0:
t = s.pop()
doSort(s)
pushSorted(s, t)
s = []
s.append(12)
s.append(5)
s.append(-3)
s.append(4)
s.append(10)

print("Stack before sorting: ")


print(s)

doSort(s)

print("\nStack after sorting: ")


print(s)
Output
Explain
Stack before sorting:
[12, 5, -3, 4, 10]

Stack after sorting:


[-3, 4, 5, 10, 12]
17.A Stack STK and Queue QUE is being maintained. Their maximum size is the same:
(i) check whether they have the same size, i.e., have the same number of elements.
(ii) check for equality of Stack and Queue, i.e.,
1. Retrieve an element from the Stack and one element from the Queue.
2. Compare the two.
3. Stop and report if elements are different.
Solution
def is_empty(stack_or_queue):
return len(stack_or_queue) == 0

def size(stack_or_queue):
return len(stack_or_queue)

def check_size_equality(stack, queue):


return size(stack) == size(queue)

def check_element_equality(stack, queue):


if check_size_equality(stack, queue) == False:
print("The size of stack and Queue is not equal.")
return False

while not is_empty(stack) and not is_empty(queue):


stack_element = stack.pop()
queue_element = queue.pop(0)

if stack_element != queue_element:
return False

return True

STK = [1, 2, 3]
QUE = [3, 2, 1]
print("Size Equality Check:", check_size_equality(STK, QUE))

print("Element Equality Check:", check_element_equality(STK, QUE))


Output
Size Equality Check: True
Element Equality Check: True

18(i)Write an algorithm to insert element into Stack as a list.


Answer
An algorithm to insert element into Stack as a list is as follows:
1. START
2. Stack = list() or Stack = [] #Initialize a Stack using list
3. element = input("Enter the value to be added in the stack: ")
4. Stack.append(element) #Adding element into list
5. END
18(ii)Write an algorithm to insert element into Queue as a list.
Answer
An algorithm to insert element into Queue as a list is as follows:
1. START
2. Queue = list() or Queue = [] #Initialize a Queue using list
3. element = input("Enter the element to be added to the Queue: ")
4. Queue.append(element) #Adding element into the list Queue
5. STOP

19.Write a program to create a Stack for storing only odd numbers out of all the numbers entered by
the user. Display the content of the Stack along with the largest odd number in the Stack.
(Hint: Keep popping out the elements from Stack and maintain the largest element retrieved so far in
a variable. Repeat till Stack is empty.)
Solution
def push(stack, item):
stack.append(item)

def pop(stack):
if stack == []:
return None
return stack.pop()

def oddStack(num):
if num % 2 == 1:
push(stack, num)

def GetLargest(stack):
elem = pop(stack)
large = elem
while elem != None:
if large < elem:
large = elem
elem = pop(stack)
return large

n = int(input("How many numbers?"))


stack = []
for i in range(n):
number = int(input("Enter number:"))
oddStack(number)
print("Stack created is", stack)
bigNum = GetLargest(stack)
print("Largest number in stack", bigNum)
Output
Explain
How many numbers?8
Enter number:1
Enter number:2
Enter number:3
Enter number:4
Enter number:5
Enter number:6
Enter number:7
Enter number:8
Stack created is [1, 3, 5, 7]
Largest number in stack 7

20.Write a program that, depending upon the user's choice, either adds or removes an element from
a Stack.
Solution
def add(stack):
h = input("Enter element: ")
stack.append(h)

def remove(stack):
if len(stack) == 0:
print("No element to delete")
else:
print("Deleted element is:", stack.pop())

stack = []
while True:
print("1. Add element")
print("2. Delete element")
print("3. Exit")
op = int(input("Enter the Choice: "))
if op == 1:
add(stack)
elif op == 2:
remove(stack)
elif op == 3:
print("Exiting program.")
break
Output
Explain
1. Add element
2. Delete element
3. Exit
Enter the Choice: 1
Enter element: 11
1. Add element
2. Delete element
3. Exit
Enter the Choice: 1
Enter element: 33
1. Add element
2. Delete element
3. Exit
Enter the Choice: 1
Enter element: 44
1. Add element
2. Delete element
3. Exit
Enter the Choice: 2
Deleted element is: 44
1. Add element
2. Delete element
3. Exit
Enter the Choice: 1
Enter element: 55
1. Add element
2. Delete element
3. Exit
Enter the Choice: 2
Deleted element is: 55
1. Add element
2. Delete element
3. Exit
Enter the Choice: 3
Exiting program.

21.Write a program that, depending upon the user's choice, either pushes or pops an element in a
Stack. The elements are shifted towards the right so that the top always remains at 0th (zeroth)
index.
Solution
def push(stack, element):
stack.insert(0, element)

def pop(stack):
if stack == []:
print("Stack is empty")
else:
print("Popped element:", stack.pop(0))

stack = []

while True:
print("STACK OPERATIONS")
print("1. Push element")
print("2. Pop element")
print("3. Exit")
choice = input("Enter your choice (1-3): ")

if choice == '1':
element = input("Enter the element to push: ")
push(stack, element)
elif choice == '2':
pop(stack)
elif choice == '3':
print("Exiting program")
break
else:
print("Invalid choice. Please enter a valid option.")
Output
Explain
STACK OPERATIONS
1. Push element
2. Pop element
3. Exit
Enter your choice (1-3): 1
Enter the element to push: 3
STACK OPERATIONS
1. Push element
2. Pop element
3. Exit
Enter your choice (1-3): 1
Enter the element to push: 6
STACK OPERATIONS
1. Push element
2. Pop element
3. Exit
Enter your choice (1-3): 1
Enter the element to push: 9
STACK OPERATIONS
1. Push element
2. Pop element
3. Exit
Enter your choice (1-3): 1
Enter the element to push: 12
STACK OPERATIONS
1. Push element
2. Pop element
3. Exit
Enter your choice (1-3): 2
Popped element: 12
STACK OPERATIONS
1. Push element
2. Pop element
3. Exit
Enter your choice (1-3): 3
Exiting program

22.Write a program to insert or delete an element from a Queue depending upon the user's choice.
The elements are not shifted after insertion or deletion.
Solution
def enqueue(queue):
element = input("Enter the element to enqueue: ")
queue.append(element)

def dequeue(queue):
if queue:
removed_element = queue.pop(0)
print("Dequeued element:", removed_element)
else:
print("Queue is empty")

queue = []

while True:
print("QUEUE OPERATIONS")
print("1. Enqueue element")
print("2. Dequeue element")
print("3. Exit")
choice = input("Enter your choice (1-3): ")

if choice == '1':
enqueue(queue)
elif choice == '2':
dequeue(queue)
elif choice == '3':
print("Exiting program")
break
else:
print("Invalid choice. Please enter a valid option.")
Output
Explain
QUEUE OPERATIONS
1. Enqueue element
2. Dequeue element
3. Exit
Enter your choice (1-3): 1
Enter the element to enqueue: 4
QUEUE OPERATIONS
1. Enqueue element
2. Dequeue element
3. Exit
Enter your choice (1-3): 1
Enter the element to enqueue: 8
QUEUE OPERATIONS
1. Enqueue element
2. Dequeue element
3. Exit
Enter your choice (1-3): 1
Enter the element to enqueue: 12
QUEUE OPERATIONS
1. Enqueue element
2. Dequeue element
3. Exit
Enter your choice (1-3): 2
Dequeued element: 4
QUEUE OPERATIONS
1. Enqueue element
2. Dequeue element
3. Exit
Enter your choice (1-3): 3
Exiting program

23.Two lists Lname and Lage contain name of person and age of person respectively. A list named
Lnameage is empty. Write functions as per details given below:
1. Push_na(): It will push the tuple containing pair of name and age from Lname and Lage
whose age is above 50.
2. Pop_na(): It will remove the last pair of name and age and also print name and age of the
removed person. It should also print "underflow" if there is nothing to remove.
For example, the two lists have the following data:
Lname=['Narender', 'Jaya', 'Raju', 'Ramesh', 'Amit', 'Piyush' ]
Lage= [45, 23, 59, 34, 51, 43]
After Push_na() the Lnameage Stack contains:
[('Raju', 59), ('Amit', 51)]
The output of first execution of Pop_na() is:
The name removed is Amit
The age of person is 51
Solution
def Push_na(Lname, Lage, Lnameage):
for i in range(len(Lname)):
if Lage[i] > 50:
Lnameage.append((Lname[i], Lage[i]))

def Pop_na(Lnameage):
if Lnameage:
removed_name, removed_age = Lnameage.pop()
print("The name removed is", removed_name)
print("The age of person is", removed_age)
else:
print("Underflow - Nothing to remove")

Lname = ['Narender', 'Jaya', 'Raju', 'Ramesh', 'Amit', 'Piyush']


Lage = [45, 23, 59, 34, 51, 43]
Lnameage = []

Push_na(Lname, Lage, Lnameage)


print("After Push_na() the Lnameage Stack contains:")
print(Lnameage)

print("\nThe output of first execution of Pop_na() is:")


Pop_na(Lnameage)
Output
Explain
After Push_na() the Lnameage Stack contains:
[('Raju', 59), ('Amit', 51)]

The output of first execution of Pop_na() is:


The name removed is Amit
The age of person is 51

24.A dictionary stu contains rollno and marks of students. Two empty lists stack_roll and stack_mark
will be used as Stack. Two functions Push_stu() and Pop_stu() are defined and perform the following
operation:
1. Push_stu(): It reads dictionary stu and adds keys into stack_roll and values into stack_marks
for all students who secured more than 60 marks.
2. Pop_stu(): It removes last rollno and marks from both list and prints "underflow" if there is
nothing to remove.
For example,
stu={ 1 : 56, 2 : 45, 3 : 78, 4 : 65, 5 : 35, 6 : 90 }
Values of stack_roll and stack_mark after push_stu() function:
[3, 4, 6] and {78, 65, 90}
Solution
def Push_stu(stu, stack_roll, stack_mark):
for rollno, marks in stu.items():
if marks > 60:
stack_roll.append(rollno)
stack_mark.append(marks)

def Pop_stu(stack_roll, stack_mark):


if stack_roll and stack_mark:
print("Removed rollno:", stack_roll.pop())
print("Removed marks:", stack_mark.pop())
else:
print("Underflow - Nothing to remove")

stu = {1: 56, 2: 45, 3: 78, 4: 65, 5: 35, 6: 90}


stack_roll = []
stack_mark = []

Push_stu(stu, stack_roll, stack_mark)


print("Values of stack_roll and stack_mark after Push_stu() function:")
print(stack_roll, stack_mark)

print("\nThe output of first execution of Pop_stu() is:")


Pop_stu(stack_roll, stack_mark)
Output
Explain
Values of stack_roll and stack_mark after Push_stu() function:
[3, 4, 6] [78, 65, 90]

The output of first execution of Pop_stu() is:


Removed rollno: 6
Removed marks: 90

25.Write AddCustomer(Customer) and DeleteCustomer(Customer) methods in Python to add a new


Customer and delete a Customer from a List of CustomerNames, considering them to act as push and
pop operations of the Stack data structure.
Solution
def AddCustomer(Customer):
Customer_name = input("Enter the customer name: ")
Customer.append(Customer_name)

def DeleteCustomer(Customer):
if Customer == []:
print("Customer list is empty")
else:
print("Deleted Customer name:", Customer.pop())

Customer = []

AddCustomer(Customer)
AddCustomer(Customer)
AddCustomer(Customer)
print("Initial Customer Stack:", Customer)

DeleteCustomer(Customer)
print("Customer Stack after deletion:", Customer)
Output
Explain
Enter the customer name: Anusha
Enter the customer name: Sandeep
Enter the customer name: Prithvi
Initial Customer Stack: ['Anusha', 'Sandeep', 'Prithvi']
Deleted Customer name: Prithvi
Customer Stack after deletion: ['Anusha', 'Sandeep']

Additional Questions:
1) You have a stack named BooksStack that contains records of books. Each book record is
represented as a list containing book_title, author_name, and publication_year. Write the
following user-defined functions in Python to perform the specified operations on the stack
BooksStack:
(I) push_book(BooksStack, new_book): This function takes the stack BooksStack and a new book
record new_book as arguments and pushes the new book record onto the stack.
(II) pop_book(BooksStack): This function pops the topmost book record from the stack and returns
it. If the stack is already empty, the function should display "Underflow".
(III) peep(BookStack): This function displays the topmost element of the stack without deleting it.
If the stack is empty, the function should display 'None'.

(I) def push_book(BooksStack, new_book):


BooksStack.append(new_book)
(II) def pop_book(BooksStack):
if not BooksStack:
print("Underflow")
else:
return(BookStack.pop())
(III) def peep(BooksStack):
if not BooksStack:
print("None")
else:
print(BookStack[-1])

2) Write a function DoubleStack(Stk), where Stk is a stack containing integers. In the function pop
all the
element of the stack and double the elements then push back to the stack in its original place.
For example:
Stk = [10,20,30,40,50]
After the execution of the function the stack should be:
Stk = [20,40,60,80,100]

Solution:
def DoubleStack(Stk):
# Create an empty list to hold popped elements
temp = []

# Pop all elements from the stack and double them


while Stk:
element = Stk.pop() # Remove the top element
temp.append(element * 2) # Double and store it in a temporary list

# Push the doubled elements back to the stack in original order


while temp:
Stk.append(temp.pop()) # Push back to stack

# Example usage
stack = [10, 20, 30, 40, 50]
DoubleStack(stack)
print(stack) # Output: [20, 40, 60, 80, 100]
3) Write the definition of a user-defined function `push_even(N)` which accepts a list of integers in
a parameter `N` and pushes all those integers which are even from the list `N` into a Stack named
`EvenNumbers`. Write function pop_even() to pop the topmost number from the stack and returns
it. If the stack is already empty, the function should display "Empty". Write function Disp_even() to
display all element of the stack without deleting them. If the stack is empty, the function should
display 'None'.
For example: If the integers input into the list `VALUES` are: [10, 5, 8, 3, 12]
Then the stack `EvenNumbers` should store: [10, 8, 12]
Solution:

4) Write the functions in python, PUSH(Stk, L) and POP(Stk), where Stk is the stack and L is a list of
strings. In PUSH function read the list and push those string into the stack which start with a
vowel. And in POP function display the stack.

Solution:
def PUSH(Stk, L):
for item in L:
if item[0].lower() in 'aeiou': # Check if the first character is a vowel
Stk.append(item) # Push the item onto the stack

def POP(Stk):
if Stk: # Check if the stack is not empty
print("Current Stack:", Stk)
else:
print("Stack is empty.")

# Example Usage
stack = []
list_of_strings = ['apple', 'banana', 'orange', 'umbrella', 'grape']
PUSH(stack, list_of_strings)
POP(stack)

You might also like