0% found this document useful (0 votes)
38 views29 pages

AIML Question Bank (1) - Key

Aiml question bank

Uploaded by

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

AIML Question Bank (1) - Key

Aiml question bank

Uploaded by

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

Mount Zion College of Engineering &

Technology
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Course Code : AD3251

Course Name : DATA STRUCTURE AND DESIGN Regulation:2021


Year/Sem : I/II
QUESTION BANK

UNIT I - ABSTRACT DATA TYPES

Abstract Data Types (ADTs) – ADTs and classes – introduction to OOP – classes in Python –
inheritance – namespaces – shallow and deep copying
Introduction to analysis of algorithms – asymptotic notations – recursion – analyzing recursive
algorithms
Univ.
Q.No Question Marks
Ques
1.1&1.2 AbstractData Type and Classes
PART A

1. Define ADT. 2 N/D 22

2. Define data structure,class,variable,data type,object


2
3. Mention the features of ADT N/D 22
2
4. What is algorithm?How to compute its time complexity?
2
5. Differentiate stack ADT and queue ADT.
2
6. What is the difference between ADT and datastructure.
2
4. List ADT.What is ADT,give example. 2 A/M 23

5. What is recursion in data structure? N/D 23


2
6. What is analysis of recursive algorithm? 2 A/M 21

7. Define data structure and how the data types are classified at the 2 N/D 23
higher level.
PART B
1. Design and implement a time date ADTthat can be used to 13 A/M 21
represent both a date and time as a single entity.
2. A click counter is a small hand-held device that contains a push 13 A/M 21
button and a count display. To increment the counter, the button
is pushed and the new count shows in the display. Clicker
counters also contain a button that can be pressed to reset the
counter to zero. Design and implement the Counter ADT that
functions as a handheldclicker.
1.3&1.4 introduction to OOP – classes in Python
PART A
1. List out the methodology in OOPS. 2
2. Define abstraction,encapsulation,inheritance,polymorphism,
constructor.
3. Define oop.give real time
4. What is data type in python?

5. What is array and operator/string in python?


Mount Zion College of Engineering &
Technology
6. List the characteristics of python.

7. Why python is Robustness?

8. Is python Adaptable?

PARTB & C

1. List out all the oop concept and explain them in detail. 2

2. Explain in short about python classes and objects. 2

3. Explain the concept of python inheritance with an example. 2

4. Different types of inheritance.

PART A

1. Define Scope. 6

2. What is namespaces? 7

3. What is built in Namespace? 15

4. Differentiate between Global namespace and local namespace. 7

5. How to copy an object in pyhon?

6. Give example for python copy methods.

7. How will you create a Reference in python?

8. Give the procedure to create a new object from original


elements.
Part B&C

1. Describe namespaces in python and its types. 13

2. Discuss the shallow and deep copying and differentiate its pros 13
and cons.
3. Difference and explain in detail about the shallow and deep copy 8
of the class with suitable example.
Introduction to analysis of algorithm &Asymptotic notations

PART A

1. What is the use of algorithm analysis? 2

2. What are the types of analysis of algorithm? 2

3. What are the challenges of experimental analysis? 2

4. What is runtime analysis of algorithm? 2

5. How to analysis the complexity of user input to an algorithm? 2

6. What is Asymptotic notation?

7. Give example for Asymptotic analysis.


Mount Zion College of Engineering &
Technology

PART B & C

1. Explain about asymptotic notation and their role in algorithmic AM 23


analysis. 15
ND 23
2. Explain the asymptotic notation in details and their types with a
analysis.
3. Explain the asymptotic notation in detail and their types with
suitable example program.
Recursion & Analyzing recursive algorithm.

PART A

1. How will you analyse the running time complexity of nested


loops? 1
2. How will you analyse the running time complexity of consecutive
statements?
3. How will you analyse the running time complexity of if-then –else
statements?
4. What is Recursion? ND,23

5. Give the procedure for drawing an English ruler using recursion. ND

6. Give procedure to find disk space using recursion.

PART B

1. Discuss the analysis of recursive algorithm with factorial 2


example.
Mount Zion College of Engineering &
Technology
Prepared By : ISWARYA. G, AP/CSE

Completion Verified by
Signature of Completion Verified
Concerned Dept.
Faculty by Dept.
HOD
HOD

Sign Sign Sign

dd/mm/ yy dd/mm/yy dd/mm/yy


Mount Zion College of Engineering &
Technology
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Course Code : AD3251

Course Name : DATA STRUCTURE AND DESIGN Regulation:2021


Year/Sem : I/II
UNIT II LINEAR STRUCTURES

List ADT – array-based implementations – linked list implementations – singly linked lists –
circularly linked lists – doubly linked lists – applications of lists – Stack ADT – Queue ADT –
double ended queues

Univ
Q.No Question Marks
Qus
2.1&2.2 List ADT & array based implementation
PART A
1. Define an array.Give example. 2 AM 23
An array is a data structure that stores a collection of elements, typically of the
same type, arranged in a contiguous block of memory. Each element in the
array is accessed using an index that represents its position within the array.
Example:
python
# Define an array in Python
my_array = [1, 2, 3, 4, 5]

# Accessing elements of the array


print(my_array[0]) # Output: 1
print(my_array[3]) # Output: 4

2. Give some example of linear structure. 2


Arrays: Elements are stored in contiguous memory locations, and access is
based on index positions.
Linked Lists: Elements are stored in nodes, where each node contains data and
a reference (or pointer) to the next node in the sequence.
Stacks: Follows the Last In, First Out (LIFO) principle, where elements are added
and removed from the same end, called the top.
Queues: Follows the First In, First Out (FIFO) principle, where elements are
added at the rear and removed from the front.

3. How list operation can be implemented using array. 2


Accessing Elements: Elements in an array can be accessed using their indices,
similar to accessing elements in a list.
Appending Elements: Elements can be appended to the end of an array by
resizing the array and placing the new element at the appropriate index.
Inserting Elements: To insert an element at a specific position in the array,
elements after that position need to be shifted to make space for the new
element.
Mount Zion College of Engineering &
Technology
Deleting Elements: Deleting an element from an array involves shifting
elements after the deleted element to fill the gap left by its removal.
Finding Length: The length of an array can be determined by counting the
number of elements in the array.

PART B & C

1. What are the various operation on array? Write a procedure to insert ab 15 AM 23


element in the middle of the array.
Various operations that can be performed on arrays include:
Accessing Elements: Retrieving the value stored at a specific index in the array.
Insertion: Adding new elements at a specified position within the array.
Deletion: Removing elements from the array, either from a specified position or
by value.
Traversal: Visiting each element of the array one by one.
Searching: Finding the index of a specific element within the array.
Sorting: Rearranging the elements of the array in ascending or descending
order.
Merging: Combining two arrays into a single array.
Splitting: Dividing an array into multiple smaller arrays.
Updating: Modifying the value of an existing element in the array.
10. Concatenation: Combining two or more arrays to create a new array.
Here's a detailed procedure to insert an element in the middle of an array:
Procedure: Inserting an Element in the Middle of an Array
Calculate the Middle Index:
Determine the middle index of the array. If the array has an odd number of
elements, this index will be (length_of_array - 1) / 2. If it has an even number of
elements, there might be multiple middle indices, and you can choose either
one.
Shift Elements to Make Space:
Start from the end of the array and move towards the middle.
For each element from the middle index towards the end, move it one position
to the right to make space for the new element.
Insert the New Element:
Once you've created enough space, insert the new element at the middle index.
Here's a Python-like pseudocode demonstrating the procedure:
def insert_in_middle(array, new_element):
# Calculate the middle index
middle_index = (len(array) - 1) // 2

# Shift elements to make space


for i in range(len(array) - 1, middle_index, -1):
array[i] = array[i - 1]

# Insert the new element at the middle index


array[middle_index] = new_element

# Example usage:
my_array = [1, 2, 3, 4, 5]
Mount Zion College of Engineering &
Technology
insert_in_middle(my_array, 99)
print(my_array) # Output: [1, 2, 99, 3, 4, 5]

2. Consider an array A[l:n]. Given a position, write an algorithm to insert an 15


element in the array. If the position is empty, the element is inserted easily. If
the position is already occupied the element should be inserted with the
minimum number of shifts.
Ans:
To insert an element into an array at a specified position with minimum shifts,
we need to follow these steps:
Check if the position is empty or already occupied.
If the position is empty, insert the element directly.
If the position is occupied, shift the elements to make space for the new
element.
Insert the new element into the specified position.
Here's a detailed algorithm:
Algorithm: Inserting an Element into an Array at a Specified Position with
Minimum Shifts
Input:
Array A with l to n elements
Position p at which the element is to be inserted
Element x to be inserted
Output:
Updated array A with element x inserted at position p
Procedure:
If the position p is greater than n or less than l, return an error indicating an
invalid position.
If position p is empty (i.e., A[p] is None or A[p] == 0 or any other indicator of an
empty position), insert the element x at position p, and return the updated
array.
If position p is already occupied: a. Shift elements from position n-1 to p to the
right by one position. b. Insert the new element x at position p. c. Return the
updated array.
def insert_element_with_min_shifts(A, l, n, p, x):
# Check if position is valid
if p < l or p > n:
return "Error: Invalid position"

# If position is empty, insert element directly


10. if A[p] is None:
11. A[p] = x
12. return A
13.
14. # Shift elements to make space for new element
15. for i in range(n, p, -1):
16. A[i] = A[i - 1]
17.
18. # Insert new element at position p
Mount Zion College of Engineering &
Technology
19. A[p] = x
20. return A
21.
22. # Example usage:
23. A = [1, 2, 3, None, 5] # Assume position 3 is empty
24. l=0
25. n=4
26. p=3
27. x=4
28. print(insert_element_with_min_shifts(A, l, n, p, x)) # Output: [1, 2, 3, 4, 5]

2.3 Linked list implementation

PART A

1. What are the advantages of linked list over array?


Dynamic Size: Linked lists can dynamically adjust their size by allocating memory
as needed. In contrast, arrays have a fixed size, and resizing them requires
allocating a new array and copying elements, which can be inefficient.
Efficient Insertions and Deletions: In a linked list, inserting or deleting elements
is typically faster than in an array. Insertions and deletions in arrays may require
shifting elements, especially if they are not at the end of the array, whereas in a
linked list, only pointer manipulations are necessary, which can be done in
constant time.

2. Differences between linear linked list and circular linked list.


Termination Point:
Linear Linked List: In a linear linked list, the last node points to None (or null),
indicating the end of the list.
Circular Linked List: In a circular linked list, the last node points back to the first
node, creating a loop, which means there is no distinct end to the list.
Traversal:
Linear Linked List: Traversing a linear linked list involves starting from the head
node and moving sequentially through each node until reaching the end (None).
Circular Linked List: Traversing a circular linked list can start from any node and
continues indefinitely in a loop, with no explicit termination point. To prevent an
infinite loop while traversing, a stopping condition based on a specific criteria
(e.g., reaching the starting node again) needs to be defined.

PART B & C

1. List out and explain various operations on linked list 15


Traversal: Traversing the linked list involves visiting each node sequentially from
the head node to the last node. This operation is essential for accessing,
displaying, or processing each element in the list.
Insertion:
Insertion at the Beginning: Adding a new node at the beginning of the linked list
involves creating a new node, setting its next pointer to the current head node,
and updating the head pointer to point to the new node.
Insertion at the End: Adding a new node at the end of the linked list requires
Mount Zion College of Engineering &
Technology
traversing the list until reaching the last node, then appending the new node to
the end by updating the next pointer of the last node to point to the new node.
Insertion at a Specific Position: To insert a node at a specific position, such as
after a given node, the pointers of adjacent nodes need to be adjusted to
accommodate the new node.
Deletion:
Deletion at the Beginning: Removing the first node of the linked list involves
updating the head pointer to point to the second node and deallocating the
memory occupied by the removed node.
Deletion at the End: Deleting the last node of the linked list requires traversing
the list until reaching the second-to-last node and updating its next pointer to
None, then deallocating the memory of the last node.
Deletion at a Specific Position: Removing a node from a specific position
involves adjusting the pointers of adjacent nodes to bypass the node to be
deleted and deallocating its memory.
Search: Searching for a specific element in the linked list involves traversing the
list from the head node until finding the target element or reaching the end of
the list.
Insertion/Deletion of Duplicate Elements: Operations to handle duplicate
elements by either inserting or deleting them based on requirements.
Reversal: Reversing the linked list involves changing the direction of pointers
such that the last node becomes the head node and each node points to its
previous node.
Concatenation: Concatenating two linked lists involves connecting the last node
of the first list to the head node of the second list, effectively joining them
together.
Splitting: Splitting a linked list into two separate lists based on a certain
condition or position.
Counting Nodes: Counting the number of nodes in the linked list by traversing
through all nodes and incrementing a counter.

2.4 Singly linked list

PART A

1. Define singly linked list with example. 2


A singly linked list is a linear data structure consisting of nodes where each node
contains a data element and a pointer to the next node in the sequence. It
follows a unidirectional flow, meaning you can only traverse the list in one
direction, typically from the head (the first node) to the tail (the last node). The
last node points to NULL, indicating the end of the list.
Example:
Node 1 Node 2 Node 3 Node 4
+-------+ +-------+ +-------+ +-------+
| Data | | Data | | Data | | Data |
+-------+ +-------+ +-------+ +-------+
| Next ----> | Next ----> | Next ----> | NULL |
+-------+ +-------+ +-------+ +-------+
| 10 | | 20 | | 30 | | 40 |
+-------+ +-------+ +-------+ +-------+
Mount Zion College of Engineering &
Technology
PART B & C

1. Develop the program in python to delete a node the minimum value from a 15
singly linked list.

To delete a node with the minimum value from a singly linked list in Python, you
need to traverse the list to find the minimum value and then delete the node
containing that value. Here's a step-by-step explanation and the corresponding
Python code:
Traverse the Linked List:
Start traversing the linked list from the head node.
Keep track of the minimum value found so far and the node that contains it.
Delete the Node:
Once you find the node with the minimum value, remove it from the linked list.
Update the pointers of the previous node to skip the node to be deleted.
Free the memory allocated to the node.
Here's the Python code implementing the above steps:
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None

def append(self, data):


new_node = Node(data)
if not self.head:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node

def delete_min_node(self):
if not self.head:
return "List is empty"

min_value = float('inf') # Initialize min_value with positive infinity


prev_node = None
current_node = self.head

# Traverse the list to find the node with minimum value


while current_node:
if current_node.data < min_value:
min_value = current_node.data
min_node = current_node
Mount Zion College of Engineering &
Technology
min_prev_node = prev_node
prev_node = current_node
current_node = current_node.next

# Delete the node with the minimum value


if min_node == self.head:
self.head = min_node.next
else:
min_prev_node.next = min_node.next
del min_node

def display(self):
current_node = self.head
while current_node:
print(current_node.data, end=" -> ")
current_node = current_node.next
print("None")

# Example usage:
if __name__ == "__main__":
linked_list = LinkedList()
linked_list.append(10)
linked_list.append(5)
linked_list.append(20)
linked_list.append(3)
linked_list.append(15)

print("Original Linked List:")


linked_list.display()

linked_list.delete_min_node()
print("\nLinked List after deleting the node with minimum value:")
linked_list.display()

2. Write an algorithm to merge two sorted linked lists into a single sorted list.
Algorithm: Merge Two Sorted Linked Lists
Input:
Head pointers of two sorted linked lists, let's call them list1_head and
list2_head.
Output:
Head pointer of the merged sorted linked list.
Procedure:
Initialize three pointers: merged_head, current, and tail.
merged_head: Points to the head of the merged list (initially None).
current: Points to the current node being processed in the merged list.
tail: Points to the last node of the merged list (initially None).
Initialize current1 and current2 pointers to the heads of list1_head and
Mount Zion College of Engineering &
Technology
list2_head, respectively.
Iterate while both current1 and current2 are not None: a. Compare the values of
current1 and current2. b. Set the next pointer of current to the node with the
smaller value. c. Move the pointer of the list with the smaller value (current1 or
current2) to its next node. d. Move current to its next node as well.
After the loop, append the remaining nodes of the non-empty list to the merged
list.
Return the merged_head, which points to the head of the merged sorted linked
list.
Here's a Python-like pseudocode implementation of the algorithm:
def merge_sorted_lists(list1_head, list2_head):
# Initialize pointers
merged_head = None
current = None
tail = None
current1 = list1_head
current2 = list2_head

# Iterate until both lists are not None


while current1 is not None and current2 is not None:
if current1.data <= current2.data:
# Set current's next to current1
if merged_head is None:
merged_head = current1
else:
current.next = current1
current = current1
current1 = current1.next
else:
# Set current's next to current2
if merged_head is None:
merged_head = current2
else:
current.next = current2
current = current2
current2 = current2.next

# Append remaining nodes of non-empty list


if current1 is not None:
if merged_head is None:
merged_head = current1
else:
current.next = current1
if current2 is not None:
if merged_head is None:
merged_head = current2
else:
current.next = current2
Mount Zion College of Engineering &
Technology
return merged_head

2.5 Circular linked list

PART A

1. differences between linear linked list and circular linked list. 2

PART B & C

1. Write the program in python to transform a circular list into a chain.


To transform a circular linked list into a chain, you need to break the circular 15 AM 23

reference by setting the next pointer of the last node to None. Here's a step-by-
step explanation and the corresponding Python code:
Find the Last Node:
Start from the head node and traverse the circular linked list until you reach the
node that points back to the head node (i.e., the last node).
Break the Circular Reference:
Once you find the last node, set its next pointer to None, effectively breaking
the circular reference.
Here's the Python code implementing the above steps:
class Node:
def __init__(self, data):
self.data = data
self.next = None

class CircularLinkedList:
def __init__(self):
self.head = None

def append(self, data):


new_node = Node(data)
if not self.head:
self.head = new_node
new_node.next = self.head # Circular reference
return
current_node = self.head
while current_node.next != self.head:
current_node = current_node.next
current_node.next = new_node
new_node.next = self.head

def transform_to_chain(self):
if not self.head or not self.head.next:
return "List is already a chain"

current_node = self.head
# Traverse until the last node
while current_node.next != self.head:
current_node = current_node.next
# Break the circular reference
Mount Zion College of Engineering &
Technology
current_node.next = None

def display(self):
if not self.head:
print("List is empty")
return
current_node = self.head
while current_node:
print(current_node.data, end=" -> ")
current_node = current_node.next
if current_node == self.head:
break
print("None")

# Example usage:
if __name__ == "__main__":
circular_list = CircularLinkedList()
circular_list.append(1)
circular_list.append(2)
circular_list.append(3)
circular_list.append(4)
circular_list.append(5)

print("Original Circular Linked List:")


circular_list.display()

circular_list.transform_to_chain()
print("\nCircular Linked List transformed into Chain:")
circular_list.display()

2.6 Doubly linked list

PART A

1. List the advantages of doubly linked list? 2


Bidirectional Traversal: Unlike singly linked lists, where traversal is
unidirectional (from head to tail), doubly linked lists allow traversal in both
directions—forward from the head to the tail and backward from the tail to the
head. This bidirectional traversal facilitates operations like reverse traversal,
which is not efficient in singly linked lists.
Efficient Insertions and Deletions: Doubly linked lists support efficient
insertions and deletions at both ends (head and tail) and at any position within
the list. In contrast, singly linked lists only support efficient insertions and
deletions at the head and require traversal to perform operations at the tail,
resulting in slower performance for certain operations.
Improved Delete Operation: Deleting a node in a doubly linked list is more
efficient compared to a singly linked list, especially when the node to be
deleted is known. In a doubly linked list, given a reference to the node, it can be
Mount Zion College of Engineering &
Technology
deleted directly without needing to traverse the list to find its predecessor
node, as required in singly linked lists.
Support for Previous Pointer: Each node in a doubly linked list contains both a
next pointer and a prev pointer, which points to the previous node in the list.
This additional pointer allows efficient backward traversal and facilitates
operations such as removing the last node or implementing algorithms that
require accessing both the current and previous nodes.
Reversal Operations: Reversing a doubly linked list is more straightforward
compared to a singly linked list. Since each node contains a reference to both
the next and previous nodes, you can simply swap the next and prev pointers
of each node to reverse the list efficiently.

2. What is doubly linked list? Explain with a diagram.


A doubly linked list is a type of linked list where each node contains a data 2
element and two pointers: one pointing to the next node in the sequence (next
pointer) and another pointing to the previous node (previous pointer). Unlike
singly linked lists, which only allow traversal in one direction (forward), doubly
linked lists support bidirectional traversal, allowing traversal in both forward
and backward directions.

Diagram:

PART B & C

1. Write a function to delete the node n from the given doubly linked list.
P q r n s t z 15
To delete a specific node n from a doubly linked list, you typically need to adjust
the pointers of the adjacent nodes (r and s in this case) to bypass the node n.
Here's a function in Python to achieve this:
class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None

def delete_node(n):
if n is None or n.next is None:
return

# If the node to be deleted is the head node


if n.prev is None:
n.next.prev = None
n = None
return

# If the node to be deleted is not the head node


n.prev.next = n.next
n.next.prev = n.prev
Mount Zion College of Engineering &
Technology
n = None

# Example usage:
if __name__ == "__main__":
# Create the doubly linked list: P -> q -> r -> n -> s -> t -> z
P = Node("P")
q = Node("q")
r = Node("r")
n = Node("n")
s = Node("s")
t = Node("t")
z = Node("z")

P.next = q
q.prev = P
q.next = r
r.prev = q
r.next = n
n.prev = r
n.next = s
s.prev = n
s.next = t
t.prev = s
t.next = z
z.prev = t

print("Original doubly linked list:")


current = P
while current:
print(current.data, end=" -> ")
current = current.next
print("None")

# Delete the node n


delete_node(n)

print("\nDoubly linked list after deleting node n:")


current = P
while current:
print(current.data, end=" -> ")
current = current.next
print("None")

2. Explain in detail doubly linked list? Explain with an diagram.


A doubly linked list is a type of linked list where each node contains two 15
pointers: one pointing to the next node in the sequence (next pointer) and
another pointing to the previous node (previous pointer). This bidirectional
linkage allows traversal in both forward and backward directions.
Mount Zion College of Engineering &
Technology
+------+ +------+ +------+ +------+ +------+

| Data | | Data | | Data | | Data | | Data |

+------+ +------+ +------+ +------+ +------+

| Prev |<--->| Prev |<--->| Prev |<--->| Prev |<--->| Prev |

+------+ +------+ +------+ +------+ +------+

| | | | |

| | | | |

v v v v v

+------+ +------+ +------+ +------+ +------+

| Next |<--->| Next |<--->| Next |<--->| Next |<--->| Next |

In a doubly linked list:


Each node contains a data field, which can hold any type of data.
Each node contains two pointers:
prev pointer: Points to the previous node in the sequence. For the first node in
the list, this pointer is usually None.
next pointer: Points to the next node in the sequence. For the last node in the
list, this pointer is usually None.
The first node of the list is called the head node, and the last node is called the
tail node.
The prev pointer of the head node is None, and the next pointer of the tail
node is also None.
Traversal can start from either the head or the tail of the list, allowing efficient
traversal in both forward and backward directions.
Insertions and deletions can be performed at any position in the list, including
the head and tail, with constant time complexity (O(1)).

3. Illustrate Illustrate the algorithms to implement the doubly linked list and 15
perform all the operations on the created list.
. Doubly Linked List Implementation:
Node Definition:
Each node of the doubly linked list contains:
Mount Zion College of Engineering &
Technology
Data: Holds the value of the node.
Pointer to the Previous Node (prev): Points to the previous node in the list.
Pointer to the Next Node (next): Points to the next node in the list.
class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
Operations on Doubly Linked List:
Insertion:
Append:
Add a new node at the end of the list.
Traverse the list until the last node, and adjust pointers accordingly.
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
new_node.prev = current
Prepend:
Add a new node at the beginning of the list.
Adjust pointers of the new node and the head node.
def prepend(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
else:
new_node.next = self.head
self.head.prev = new_node
self.head = new_node
Deletion:
Delete:
Remove a node with a given value from the list.
Traverse the list until finding the node with the value to be deleted.
Adjust pointers of the previous and next nodes to bypass the node to be
deleted.
def delete(self, value):
if not self.head:
return
current = self.head
while current:
if current.data == value:
if current == self.head:
self.head = current.next
if self.head:
self.head.prev = None
else:
current.prev.next = current.next
if current.next:
current.next.prev = current.prev
Mount Zion College of Engineering &
Technology
return
current = current.next
Traversal:
Display Forward:
Traverse the list from the head to the last node and print each node's value.
def display_forward(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
Display Backward:
Traverse the list from the last node to the head and print each node's value.
def display_backward(self):
current = self.head
while current and current.next:
current = current.next
while current:
print(current.data, end=" -> ")
current = current.prev
print("None")

2.7 Application of lists


PART A
1. Give the three application of linked list. 2
Memory Management in Operating Systems:
Linked lists are extensively used in memory management systems of operating
systems.
Dynamic memory allocation using techniques like malloc() and free() in C
programming language often involves linked lists.
In systems with limited memory, linked lists allow for efficient allocation and
deallocation of memory blocks of varying sizes.
Implementation of Stacks and Queues:
Linked lists are fundamental in implementing abstract data types like stacks and
queues.
Stacks and queues can be efficiently implemented using singly linked lists,
where insertions and deletions are performed at the beginning and end of the
list, respectively.
In stacks, items are added and removed in a Last-In-First-Out (LIFO) order,
whereas in queues, items are added at the rear and removed from the front in
a First-In-First-Out (FIFO) order.
Representation of Sparse Matrices:
Linked lists are suitable for representing sparse matrices, where most of the
elements are zero.
Each row of the matrix can be represented as a linked list of non-zero elements.
This representation saves memory compared to using dense matrices, as it only
stores non-zero elements along with their row and column indices.
Operations like addition, multiplication, and transpose of sparse matrices can
be efficiently implemented using linked list representations.
Mount Zion College of Engineering &
Technology

2. Evaluate given postfix expression. 2


ABC-BA+C $ for A=1, B=2, and C=3
Iteration 1: Push 1 onto the stack
Stack: [1]

Iteration 2: Push 2 onto the stack


Stack: [1, 2]

Iteration 3: Push 3 onto the stack


Stack: [1, 2, 3]

Iteration 4: Pop 3, 2 from the stack, and calculate 3 - 2 = 1. Push 1 onto the
stack
Stack: [1, 1]

Iteration 5: Pop 1, 1 from the stack, and calculate 1 - 1 = 0. Push 0 onto the
stack
Stack: [0]

Iteration 6: Pop 2, 0 from the stack, and calculate 2 + 0 = 2. Push 2 onto the
stack
Stack: [2]

Iteration 7: Pop 1, 2 from the stack, and calculate 1 + 2 = 3. Push 3 onto the
stack
Stack: [3]

At the end, the result is the top element of the stack, which is 3.
3. Write the postfix form for the expression -A+B+C+D? 2
Input: -A+B+C+D
Output: AB-C+D+

Step-by-step conversion:
- Initialize an empty stack and an empty list.
- Iterate through each token in the infix expression:
- Token: - (operator)
- Stack is empty, so push '-' onto the stack.
- Token: A (operand)
- Add 'A' to the postfix expression list.
- Token: + (operator)
- Pop '-' from the stack and add it to the postfix expression list.
- Push '+' onto the stack.
- Token: B (operand)
- Add 'B' to the postfix expression list.
- Token: + (operator)
- Pop '+' from the stack and add it to the postfix expression list.
- Push '+' onto the stack.
Mount Zion College of Engineering &
Technology
- Token: C (operand)
- Add 'C' to the postfix expression list.
- Token: + (operator)
- Pop '+' from the stack and add it to the postfix expression list.
- Push '+' onto the stack.
- Token: D (operand)
- Add 'D' to the postfix expression list.
- Pop any remaining operators from the stack and add them to the postfix
expression list.
- Final postfix expression: AB-C+D+
4. What are the postfix and prefix forms of the expression?
PART B & C
1. Explain how polynomial expression can represented using linked list 15
Polynomial expressions can be represented efficiently using linked lists, where
each term of the polynomial is represented by a node in the linked list. Each
node typically contains two fields:
Coefficient: Represents the coefficient of the term.
Exponent: Represents the exponent of the term.

𝑃(𝑥)=3𝑥2+2𝑥−5P(x)=3x2+2x−5
For example, consider the polynomial expression:

This polynomial can be represented using a linked list as follows:


Create a node for each term:
Node 1: Coefficient = 3, Exponent = 2
Node 2: Coefficient = 2, Exponent = 1
Node 3: Coefficient = -5, Exponent = 0
Link these nodes together to form a linked list.
class Term:
def __init__(self, coefficient, exponent):
self.coefficient = coefficient
self.exponent = exponent
self.next = None

class Polynomial:
10. def __init__(self):
11. self.head = None
12.
13. def add_term(self, coefficient, exponent):
14. new_term = Term(coefficient, exponent)
15. if not self.head:
16. self.head = new_term
17. else:
18. current = self.head
19. while current.next:
20. current = current.next
21. current.next = new_term
22.
23. def display(self):
24. current = self.head
Mount Zion College of Engineering &
Technology
25. while current:
26. print(f"{current.coefficient}x^{current.exponent}", end=" + " if
current.next else "")
27. current = current.next
28. print("")
29.
30. # Example usage:
31. if __name__ == "__main__":
32. poly = Polynomial()
33. poly.add_term(3, 2)
34. poly.add_term(2, 1)
35. poly.add_term(-5, 0)
36.
37. print("Polynomial Representation:")
38. poly.display()

2. Write a function to add two polynomials using linked list 15


class Term:
def __init__(self, coefficient=0, exponent=0):
self.coefficient = coefficient
self.exponent = exponent
self.next = None

class Polynomial:
def __init__(self):
self.head = None

def add_term(self, coefficient, exponent):


new_term = Term(coefficient, exponent)
if not self.head:
self.head = new_term
else:
current = self.head
while current.next:
current = current.next
current.next = new_term

def display(self):
current = self.head
while current:
print(f"{current.coefficient}x^{current.exponent}", end=" + " if
current.next else "")
current = current.next
print("")

def add_polynomials(self, poly1, poly2):


result_poly = Polynomial()
current1 = poly1.head
current2 = poly2.head
Mount Zion College of Engineering &
Technology
while current1 and current2:
if current1.exponent == current2.exponent:
result_poly.add_term(current1.coefficient + current2.coefficient,
current1.exponent)
current1 = current1.next
current2 = current2.next
elif current1.exponent > current2.exponent:
result_poly.add_term(current1.coefficient, current1.exponent)
current1 = current1.next
else:
result_poly.add_term(current2.coefficient, current2.exponent)
current2 = current2.next

while current1:
result_poly.add_term(current1.coefficient, current1.exponent)
current1 = current1.next

while current2:
result_poly.add_term(current2.coefficient, current2.exponent)
current2 = current2.next

return result_poly

# Example usage:
if __name__ == "__main__":
# Create first polynomial: 3x^2 + 2x - 5
poly1 = Polynomial()
poly1.add_term(3, 2)
poly1.add_term(2, 1)
poly1.add_term(-5, 0)

# Create second polynomial: 4x^3 + 2x^2 + 6x + 1


poly2 = Polynomial()
poly2.add_term(4, 3)
poly2.add_term(2, 2)
poly2.add_term(6, 1)
poly2.add_term(1, 0)

# Add the two polynomials


result = Polynomial().add_polynomials(poly1, poly2)

# Display the result


print("Resultant Polynomial:")
result.display()
Mount Zion College of Engineering &
Technology
2.8 Stack ADT

PART A

1. Define stack
A stack is a linear data structure that follows the Last In, First Out (LIFO) 2
principle, meaning that the last element added to the stack is the first one to be
removed. It can be visualized as a collection of elements with two primary
operations: push and pop.
Push: Adds an element to the top of the stack.
Pop: Removes the element from the top of the stack.
Stacks typically support other operations such as peek (viewing the top element
without removing it) and isEmpty (checking if the stack is empty). They are
commonly used in various applications such as expression evaluation, function
call management, undo mechanisms, and more.
2. What are the various operations performed on the stack?
Push: Adds an element to the top of the stack. 2

Pop: Removes the top element from the stack.


Peek (or Top): Returns the value of the top element without removing it from
the stack.
isEmpty: Checks if the stack is empty. Returns true if the stack is empty;
otherwise, returns false.
isFull: Checks if the stack is full (applicable in fixed-size stack implementations).
Returns true if the stack is full; otherwise, returns false.
Size (or Length): Returns the number of elements currently in the stack.

3. List any four application of stack with relevant example 2


Expression Evaluation:
Stacks are widely used in evaluating expressions, including infix, postfix, and
prefix expressions.
In infix expression evaluation, stacks help maintain the order of operators based
on their precedence.
In postfix and prefix expression evaluation, stacks are used to perform
operations in the correct order.
Function Call Management:
Stacks play a crucial role in managing function calls and returns in programming
languages.
When a function is called, its parameters and return address are pushed onto
the stack.
After the function completes execution, its return value is popped from the
stack, and control returns to the calling function.
Memory Management:
Stacks are used in memory management systems to allocate and deallocate
memory.
Stack memory is utilized for storing local variables and function calls.
Memory allocation and deallocation operations are implemented using stack
operations, providing a simple and efficient memory management mechanism.
Backtracking and Search Algorithms:
Stacks are essential in backtracking algorithms, such as depth-first search (DFS)
in graph traversal.
During exploration, nodes and their states are pushed onto the stack.
Backtracking involves popping nodes from the stack to explore other paths,
making stacks an integral part of search algorithms.
Mount Zion College of Engineering &
Technology
These applications highlight the importance of stacks in computer science and
software development, enabling e

4. Show the simulation using stack with for the following expression to
convert infix to postfix:p*q+(r-s/t) 2

Given infix expression: 𝑝∗𝑞+(𝑟−𝑠/𝑡)p∗q+(r−s/t)

Tokens: 𝑝p, ∗∗, 𝑞q, ++, ((, 𝑟r, −−, 𝑠s, //, 𝑡t, ))

Postfix expression:

Start with an empty stack and an empty output list.


Iterate through each token:
𝑝p: Add to output list.
∗∗: Push onto stack.
𝑞q: Add to output list.
++: Pop ∗∗ from stack and add to output list. Push ++ onto stack.
((: Push onto stack.
𝑟r: Add to output list.
−−: Push onto stack.
𝑠s: Add to output list.
//: Push onto stack.
𝑡t: Add to output list.
)): Pop operators from stack until (( is encountered. Add popped operators to
output list. Discard ((.
Pop remaining operators from stack and add to output list.

Postfix expression: 𝑝 𝑞 ∗ 𝑟 𝑠 𝑡 / − +pq∗rst/−+

PART B & C

1. Explain the linked list implementation of stack ADT in detail?


Def:2m imlementatio:8m program:5m 15

2.9 Queue ADT

PART A

1. Define queue 2
A queue is a linear data structure that follows the First In, First Out (FIFO)
principle, meaning that the element that is added first to the queue will be the
first one to be removed. It can be visualized as a collection of elements with
two primary operations: enqueue and dequeue.
Enqueue: Adds an element to the rear of the queue.
Mount Zion College of Engineering &
Technology
Dequeue: Removes the element from the front of the queue.

2. Differentiate stack ADT and queue ADT. 2


Principle of Access:
Stack: Follows the Last In, First Out (LIFO) principle. The last element added to
the stack is the first one to be removed.
Queue: Follows the First In, First Out (FIFO) principle. The element that is added
first to the queue will be the first one to be removed.
Primary Operations:
Stack: Supports operations like push (to add elements) and pop (to remove
elements).
Queue: Supports operations like enqueue (to add elements) and dequeue (to
remove elements).

3. Define circular queue. 2


A circular queue is a linear data structure that follows the First In, First Out
(FIFO) principle, similar to a standard queue, but with a circular arrangement of
elements in memory. In a circular queue, the last element is connected to the
first element, forming a circular arrangement. This circular arrangement allows
for efficient usage of memory and avoids wastage of space.
Here are some key characteristics and operations of a circular queue:
Circular Arrangement:
In a circular queue, the elements are stored in a fixed-size array.
When elements are enqueued (added to the queue), they are placed at the rear
(tail) of the queue.
When elements are dequeued (removed from the queue), they are removed
from the front (head) of the queue.
If the rear of the queue reaches the end of the array, the next element is
enqueued at the beginning of the array, effectively forming a circular
arrangement.
Operations:
Enqueue (Insertion): Adds an element to the rear of the circular queue.
Dequeue (Deletion): Removes an element from the front of the circular queue.
Front: Returns (but does not remove) the element at the front of the circular
queue.
Rear: Returns (but does not remove) the element at the rear of the circular
queue.
isEmpty: Checks if the circular queue is empty.
isFull: Checks if the circular queue is full.
Size: Returns the number of elements currently in the circular queue.
Circular Movement:
When the rear pointer reaches the end of the array, it wraps around to the
beginning if there is space available, effectively forming a circular movement.
Similarly, when the front pointer reaches the end of the array, it wraps around
to the beginning if there are elements present, maintaining the circular
arrangement.

4. Write a routine to implemented the circular queue using array 2


Mount Zion College of Engineering &
Technology
Implementation of circular queue:2m
PART B & C

5. What is dequeue? Explain its types and its operations with example. 15
Def:2m operation:10m example:3m
2.10 Double ended queues

PART B & C

2. Differentiate between double ended queue and circular queue. 15


Diff:12points
Mount Zion College of Engineering &
Technology
Prepared by : Iswarya.G., AP/CSE

Signature of Completion Verified Completion Verified by


Faculty by Dept. Concerned Dept.
HOD HOD

Sign Sign Sign

dd/mm/ yy
dd/mm/yy dd/mm/yy
Mount Zion College of Engineering &
Technology

You might also like