0% found this document useful (0 votes)
439 views34 pages

Unit-2: Searching, Sorting, Linked Lists: 2M Questions

The document contains questions related to data structures and algorithms concepts like searching, sorting, linked lists, stacks, queues etc. It includes 2 mark questions, 8 mark questions and their program implementations. Some questions ask for definitions and differences between various concepts while others ask to write programs for sorting, searching algorithms and implementing linked lists, stacks and queues.

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)
439 views34 pages

Unit-2: Searching, Sorting, Linked Lists: 2M Questions

The document contains questions related to data structures and algorithms concepts like searching, sorting, linked lists, stacks, queues etc. It includes 2 mark questions, 8 mark questions and their program implementations. Some questions ask for definitions and differences between various concepts while others ask to write programs for sorting, searching algorithms and implementing linked lists, stacks and queues.

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

11. Explain in detail about Abstraction with an example program.

12. Differences between Run time Polymorphism and Compile time polymorphism.
13. What is Encapsulation. Explain with an example program.
14. Write a python program which calculates areas of square, rectangle, circle using
Abstraction concept.
ALL LAB PROGRAMS OF UNIT-1

Unit-2 : Searching, Sorting, Linked Lists


2M Questions
1. Define Internal Sorting
2. Define External Sorting
3. What is need of Priority Queues.
4. What is a Circular Linked list.
5. Define Linked list.
6. What is deque.
7. List three differences between Bubble sort and selection sort.
8. List three differences between selection sort and insertion sort.
9. How many iterations are possible to sort a list of 120 numbers using Bubble Sort technique?
10. How many iterations are possible to sort a list of 120 numbers using Insertion Sort technique?
11. How many iterations are possible to sort a list of 120 numbers using Selection Sort technique?
12. What is Sorting? List at least 3 types of sorting techniques.
13. In Which type of Linked List there will not be None/null pointer in the address/Next field.
14. List the basic operations carried out in a linked list
15. How many types of Searching techniques we have. Among them which is the best
technique.

8M Questions:
1. Explain the following searching techniques with examples 1.Linear search 2.Binary
search
2. What is a single linked list? Explain Different operations on single linked list
3. Write algorithm and program for implementing Binary search
4. Write algorithm and program for implementing Linear search
5. Write a program for implementing a singly linked list.
6. Explain in detail about Insertion Sort with an example python program.
7. Explain in detail about Selection Sort with an example python program.
8. Explain in detail about Bubble Sort with an example python program.
9. Write a Python program to Insert a node at the beginning and end and to delete a node at the
beginning and end of circular linked list.
10. Write a Python program to Insert a node at the beginning and end and to delete a node at the
beginning and end of doubly linked list.
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


Unit-2 : Searching, Sorting, Linked Lists
2M Questions
1. Define Internal Sorting
A)
Internal sorting are type of sorting which is used when the entire collection
of data is small enough that sorting can take place within main memory.
There is no need for external memory for execution of sorting program. It
is used when size of input is small.Examples:- Bubble sort, insertion
sort,quick sort, heap sort.

2. Define External Sorting


A)
External sorting is a class of sorting algorithms that can handle massive
amounts of data.In the sorting phase, chunks of data small enough to fit in
main memory are read, sorted, and written out to a temporary file. In the
merge phase, the sorted sub files are combined into a single larger file.

3. What is need of Priority Queues.


A)
The priority queue (also known as the fringe) is used to keep track of
unexplored routes, the one for which a lower bound on the total path
length is smallest is given highest priority. Heap Sort : Heap sort is
typically implemented using Heap which is an implementation of Priority
Queue.

4. What is a Circular Linked list.


A)
A circular linked list is similar to a linked list in that the nodes are
connected by links, but the last node is also linked to the first node instead
of just linking to nothing. So, after we've accessed the last node, we can
access the first node through the last node.Circular lists are used in
applications where the entire list is accessed one-by-one in a loop

5. Define Linked list.


A)
A linked list is a sequence of data elements, which are connected together
via links. Each data element contains a connection to another data
element in form of a pointer. Python does not have linked lists in its
standard library.In this type of data structure there is only one link between
any two data elements.
6. What is deque.
A)
A double-ended queue, or deque, has the feature of adding and removing
elements from either end. The Deque module is a part of collections library.
It has the methods for adding and removing elements which can be
invoked directly with arguments

7. List three differences between Bubble sort and selection sort.


A)
Bubble sort Selection sort
In bubble sort, two adjacent In selection sort, the minimum
elements are compared. If the element is selected from the array
adjacent elements are not at the and swap with an element which is
correct position, swapping would be at the beginning of the unsorted sub
performed. array.
The time complexities in best case The time complexity in both best
and worst case are O(n) and O(n2) and worst cases is O(n 2).
respectively.
It is not an efficient sorting It is an efficient sorting technique as
technique. compared to Bubble sort.
It uses an exchanging method. It uses a selection method.
It is slower than the selection sort as It is faster than the bubble sort as a
a greater number of comparisons is lesser number of comparisons is
required. required.

8. List three differences between selection sort and insertion sort.


A)
S.NO Insertion Sort Selection Sort
1 Inserts the value in the Finds the minimum/ maximum
presorted array to sort the set number from the list and sort it in
of values in the array. ascending/descending order.
2 It is a stable sorting algorithm. It is an unstable sorting algorithm.
3 The best-case time There is no best case the time
complexity is O(N) when the complexity is O(N2) in all cases.
array is already in ascending
order.
4 The number of comparison The number of comparison
operations performed in this operations performed in this
sorting algorithm is less than sorting algorithm is more than the
the swapping performed. swapping performed.
5 It is more efficient than the It is less efficient than the
Selection sort. Insertion sort.

9. How many iterations are possible to sort a list of 120 numbers


using Bubble Sort technique?
A)
The bubble sort makes (n – 1) iterations to sort the list where n is the total
number of elements in the list

10. How many iterations are possible to sort a list of 120 numbers
using Insertion Sort technique?
A)
Insertion sort does N - 1 comparisons if the input is already sorted. This is
because for every element it compares it with a previous element and
does something if the order is not right

11. How many iterations are possible to sort a list of 120 numbers
using Selection Sort technique?
A)
The loop in indexOfMinimum will always make n2/2 + n/2 n2/2 + n/2 n2/2 +
n/2n, squared, slash, 2, plus, n, slash, 2 iterations, regardless of the input.
Therefore, we can say that selection sort runs in θ( n2 ) \θ(n2) θ(n2)\θ, left
parenthesis, n, squared, right parenthesis time in all cases.

12. What is Sorting? List at least 3 types of sorting techniques.


A)
Sorting is the processing of arranging the data in ascending and
descending order.There are several types of sorting in data structures
namely – bubble sort, insertion sort, selection sort, bucket sort, heap sort,
quick sort, radix sort etc.

13. In Which type of Linked List there will not be None/null pointer
in the address/Next field.
A)
A list in which last node points back to the header node is called circular
linked list. The chains do not indicate first or last nodes. In this case,
external pointers provide a frame of reference because last node of a
circular linked list does not contain the NULL pointer.

14. List the basic operations carried out in a linked list


A)
Basic Operations on Linked List
● Traversal: To traverse all the nodes one after another.
● Insertion: To add a node at the given position.
● Deletion: To delete a node.
● Searching: To search an element(s) by value.
● Updating: To update a node.
● Sorting: To arrange nodes in a linked list in a specific order.
15. How many types of Searching techniques we have. Among
them which is the best technique.
A)
There are 2 types of search linear and binary Search, Linear search
algorithm is straightforward and has O(n) of complexity whereas Binary
Search is a high-speed searching algorithm having the complexity of (logn)
but can only be used in case of the sorted list of elements.

Binary search is a very fast and efficient searching technique. It requires


the list to be in sorted order. In this method, to search an element you can
compare it with the present element at the center of the list.

8M Questions :
1. Explain the following searching techniques with examples
1.Linear search 2.Binary search
A)
Linear search : Linear search is a very basic and simple search
algorithm. In Linear search, we search an element or value in a given
array by traversing the array from the starting, till the desired element or
value is found.

It compares the element to be searched with all the elements present in


the array and when the element is matched successfully, it returns the
index of the element in the array, else it return -1.

Linear Search is applied on unsorted or unordered lists, when there are


fewer elements in a list.

Example:

def search(arr, n, x):

for i in range(0, n):

if (arr[i] == x):

return i
return -1

# Driver Code

arr = [2, 3, 4, 10, 40]

x = 10

n = len(arr)

# Function call

result = search(arr, n, x)

if(result == -1):

print("Element is not present in array")

else:

print("Element is present at index", result)

Output
Element is present at index 3
Binary Search :Binary Search is applied on the sorted array or list of
large size. It's time complexity of O(log n) makes it very fast as compared
to other sorting algorithms. The only limitation is that the array or list of
elements must be sorted for the binary search algorithm to work on it.

def binarySearch (arr, l, r, x):

# Check base case

if r >= l:

mid = l + (r - l) // 2

# If element is present at the middle itself


if arr[mid] == x:

return mid

# If element is smaller than mid, then it

# can only be present in left subarray

elif arr[mid] > x:

return binarySearch(arr, l, mid-1, x)

# Else the element can only be present

# in right subarray

else:

return binarySearch(arr, mid + 1, r, x)

else:

# Element is not present in the array

return -1

# Driver Code

arr = [ 2, 3, 4, 10, 40 ]

x = 10

# Function call

result = binarySearch(arr, 0, len(arr)-1, x)

if result != -1:

print ("Element is present at index % d" % result)

else:
print ("Element is not present in array")

Output :
Element is present at index 3

2. What is a single linked list? Explain Different operations on


single linked list
A)
A singly linked list is a type of linked list that is unidirectional, that is, it
can be traversed in only one direction from head to the last node (tail).
Each element in a linked list is called a node. A single node
contains data and a pointer to the next node which helps in maintaining
the structure of the list.
The first node is called the head; it points to the first node of the list and
helps us access every other element in the list. The last node, also
sometimes called the tail, points to NULL which helps us in determining
when the list ends.

Common Singly Linked List Operations:

1.Search for a node in the List

You can determine and retrieve a specific node either from the front, the
end, or anywhere in the list.
The worst case Time Complexity for retrieving a node from anywhere in
the list is O(n).

2.Add a node to the List


You can add a node at the front, the end or anywhere in the linked list.
The worst case Time Complexity for performing these operations is as
follows:

 Add item to the front of the list: O(1)


 Add item to the end of the list: O(n)
 Add item to anywhere in the list: O(n)

3.Remove a node from the list


You can remove a node either from the front, the end or from anywhere in
the list.
The worst case Time Complexity for performing this operation is as
follows:

 Remove item from the front of the list: O(1)


 Remove item from the end of the list: O(n)
 Remove item from anywhere in the list: O(n)

3. Write algorithm and program for implementing Binary search


A) algorithm:
this search algorithm takes advantage of a collection of elements that is
already sorted by ignoring half of the elements after just one
comparison.
1. Compare x with the middle element.
2. If x matches with the middle element, we return the mid index.
3. Else if x is greater than the mid element, then x can only lie in
the right (greater) half subarray after the mid element. Then we
apply the algorithm again for the right half.
4. Else if x is smaller, the target x must lie in the left (lower) half. So
we apply the algorithm for the left half.
Program:

def binary_search(arr, low, high, x):

# Check base case

if high >= low:

mid = (high + low) // 2

# If element is present at the middle itself

if arr[mid] == x:

return mid

# If element is smaller than mid, then it can only


# be present in left subarray

elif arr[mid] > x:

return binary_search(arr, low, mid - 1, x)

# Else the element can only be present in right subarray

else:

return binary_search(arr, mid + 1, high, x)

else:

# Element is not present in the array

return -1

# Test array

arr = [ 2, 3, 4, 10, 40 ]

x = 10

# Function call

result = binary_search(arr, 0, len(arr)-1, x)

if result != -1:

print("Element is present at index", str(result))

else:

print("Element is not present in array")

Output:
Element is present at index 3

4. Write algorithm and program for implementing Linear search


A) Algorithm
A simple approach is to do a linear search, i.e
 Start from the leftmost element of arr[] and one by one compare
x with each element of arr[]
 If x matches with an element, return the index.
 If x doesn’t match with any of elements, return -1.

Program

def search(arr, n, x):

for i in range(0, n):

if (arr[i] == x):

return i

return -1

# Driver Code

arr = [2, 3, 4, 10, 40]

x = 10

n = len(arr)

# Function call
result = search(arr, n, x)

if(result == -1):

print("Element is not present in array")

else:

print("Element is present at index", result)

Output
Element is present at index 3

5. Write a program for implementing a singly linked list.


A) Algorithm
1. Create a class Node which has two attributes: data and next. Next is
a pointer to the next node.
2. Create another class which has two attributes: head and tail.
3. addNode() will add a new node to the list:
a. Create a new node.
b. It first checks, whether the head is equal to null which means the list
is empty.
c. If the list is empty, both head and tail will point to the newly added
node.
d. If the list is not empty, the new node will be added to end of the list
such that tail's next will point to the newly added node. This new
node will become the new tail of the list.
4. display() will display the nodes present in the list:
. Define a node current which initially points to the head of the list.
a. Traverse through the list till current points to null.
b. Display each node by making current to point to node next to it
in each iteration.

Solution
Python
1. #Represent a node of the singly linked list
2. class Node:
3. def __init__(self,data):
4. self.data = data;
5. self.next = None;
6.
7. class SinglyLinkedList:
8. #Represent the head and tail of the singly linked list
9. def __init__(self):
10. self.head = None;
11. self.tail = None;
12.
13. #addNode() will add a new node to the list
14. def addNode(self, data):
15. #Create a new node
16. newNode = Node(data);
17.
18. #Checks if the list is empty
19. if(self.head == None):
20. #If list is empty, both head and tail will point to new nod
e
21. self.head = newNode;
22. self.tail = newNode;
23. else:
24. #newNode will be added after tail such that tail's next w
ill point to newNode
25. self.tail.next = newNode;
26. #newNode will become new tail of the list
27. self.tail = newNode;
28.
29. #display() will display all the nodes present in the list
30. def display(self):
31. #Node current will point to head
32. current = self.head;
33.
34. if(self.head == None):
35. print("List is empty");
36. return;
37. print("Nodes of singly linked list: ");
38. while(current != None):
39. #Prints each node by incrementing pointer
40. print(current.data),
41. current = current.next;
42.
43. sList = SinglyLinkedList();
44.
45. #Add nodes to the list
46. sList.addNode(1);
47. sList.addNode(2);
48. sList.addNode(3);
49. sList.addNode(4);
50.
51. #Displays the nodes present in the list
52. sList.display();

Output:

Nodes of singly linked list:


1234

6. Explain in detail about Insertion Sort with an example python


program.
A)
Insertion sort is a simple sorting algorithm that works similar to the way
you sort playing cards in your hands. The array is virtually split into a
sorted and an unsorted part. Values from the unsorted part are picked
and placed at the correct position in the sorted part.
Algorithm
To sort an array of size n in ascending order:
1: Iterate from arr[1] to arr[n] over the array.
2: Compare the current element (key) to its predecessor.
3: If the key element is smaller than its predecessor, compare it to the
elements before. Move the greater elements one position up to make
space for the swapped element.

def insertionSort(arr):

# Traverse through 1 to len(arr)

for i in range(1, len(arr)):

key = arr[i]
# Move elements of arr[0..i-1], that are

# greater than key, to one position ahead

# of their current position

j = i-1

while j >=0 and key < arr[j] :

arr[j+1] = arr[j]

j -= 1

arr[j+1] = key

# Driver code to test above

arr = [12, 11, 13, 5, 6]

insertionSort(arr)

print ("Sorted array is:")

for i in range(len(arr)):

print ("%d" %arr[i])

# This code is contributed by Mohit Kumra

Output:
Sorted array is:
5
6
11
12
13
7. Explain in detail about Selection Sort with an example python
program.
A)
The selection sort algorithm sorts an array by repeatedly finding the
minimum element (considering ascending order) from unsorted part
and putting it at the beginning. The algorithm maintains two subarrays
in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering
ascending order) from the unsorted subarray is picked and moved to
the sorted subarray.

# Python program for implementation of Selection

# Sort

import sys

A = [64, 25, 12, 22, 11]

# Traverse through all array elements

for i in range(len(A)):

# Find the minimum element in remaining

# unsorted array

min_idx = i

for j in range(i+1, len(A)):

if A[min_idx] > A[j]:

min_idx = j

# Swap the found minimum element with

# the first element


A[i], A[min_idx] = A[min_idx], A[i]

# Driver code to test above

print ("Sorted array")

for i in range(len(A)):

print("%d" %A[i]),

Output:
Sorted array:
11 12 22 25 64

8. Explain in detail about Bubble Sort with an example python


program.
A)

Bubble Sort is a sorting algorithm used to sort list items in ascending


order by comparing two adjacent values. If the first value is higher than
second value, the first value takes the second value position, while second
value takes the first value position. If the first value is lower than the
second value, then no swapping is done.

This process is repeated until all the values in a list have been compared
and swapped if necessary. Each iteration is usually called a pass. The
number of passes in a bubble sort is equal to the number of elements in a
list minus one.

# Python program for implementation of Bubble Sort

def bubbleSort(arr):

n = len(arr)

# Traverse through all array elements

for i in range(n):
# Last i elements are already in place

for j in range(0, n-i-1):

# traverse the array from 0 to n-i-1

# Swap if the element found is greater

# than the next element

if arr[j] > arr[j+1] :

arr[j], arr[j+1] = arr[j+1], arr[j]

# Driver code to test above

arr = [64, 34, 25, 12, 22, 11, 90]

bubbleSort(arr)

print ("Sorted array is:")

for i in range(len(arr)):

print ("%d" %arr[i]),

Output:

Sorted array:
11 12 22 25 34 64 90

9. Write a Python program to Insert a node at the beginning and


end and to delete a node at the beginning and end of circular
linked list.
A)
PROGRAM for insertion
1. #Represents the node of list.
2. class Node:
3. def __init__(self,data):
4. self.data = data;
5. self.next = None;
6.
7. class CreateList:
8. #Declaring head and tail pointer as null.
9. def __init__(self):
10. self.head = Node(None);
11. self.tail = Node(None);
12. self.head.next = self.tail;
13. self.tail.next = self.head;
14.
15. #This function will add at the start of the list.
16. def addAtStart(self,data):
17. newNode = Node(data);
18. #Checks if the list is empty.
19. if self.head.data is None:
20. #If list is empty, both head and tail would point to new node
.
21. self.head = newNode;
22. self.tail = newNode;
23. newNode.next = self.head;
24. else:
25. #Store data into temporary node
26. temp = self.head;
27. #New node will point to temp as next node
28. newNode.next = temp;
29. #New node will be the head node
30. self.head = newNode;
31. #Since, it is circular linked list tail will point to head.
32. self.tail.next = self.head;
33.
34. #Displays all the nodes in the list
35. def display(self):
36. current = self.head;
37. if self.head is None:
38. print("List is empty");
39. return;
40. else:
41. print("Adding nodes to the start of the list: ");
42. #Prints each node by incrementing pointer.
43. print(current.data),
44. while(current.next != self.head):
45. current = current.next;
46. print(current.data),
47. print("\n");
48.
49. class CircularLinkedList:
50. cl = CreateList();
51.
52. #Adding 1 to the list
53. cl.addAtStart(1);
54. cl.display();
55. #Adding 2 to the list
56. cl.addAtStart(2);
57. cl.display();
58. #Adding 3 to the list
59. cl.addAtStart(3);
60. cl.display();
61. #Adding 4 to the list
62. cl.addAtStart(4);
63. cl.display();

Output:

Adding nodes to the start of the list:


1
Adding nodes to the start of the list:
21
Adding nodes to the start of the list:
321
Adding nodes to the start of the list:
4321

class CSLL:
def __init__(self):
self.start_node = None
def insert_last(self, value):
new_node = Node(value) # create new node
# empty list case
if self.start_node is None:
self.start_node = new_node
self.start_node.next = self.start_node
else: # non_empty list
temp = self.start_node
while temp.next is not self.start_node:
temp = temp.next
# insert the node here
new_node.next = self.start_node
temp.next = new_node
def display(self):
# non empty list
if self.start_node is not None:
temp = self.start_node
while temp.next is not self.start_node:
print(temp.data)
temp = temp.next
print(temp.data)
s1 = CSLL()
# create list by calling insert_last
for i in range(10,50,10):
s1.insert_last(i)
s1.insert_last(100)
s1.display()
output
10
20
30
40
100
delete a node at end
class CSLL:
def __init__(self):
self.start_node = None
def insert_last(self, value):
new_node = Node(value) # create new node
# empty list case
if self.start_node is None:
self.start_node = new_node
self.start_node.next = self.start_node
else: # non_empty list
temp = self.start_node
while temp.next is not self.start_node:
temp = temp.next
# insert the node here
new_node.next = self.start_node
temp.next = new_node
def display(self):
# non empty list
if self.start_node is not None:
temp = self.start_node
while temp.next is not self.start_node:
print(temp.data, end= ' ')
temp = temp.next
print(temp.data)
def delete_last(self):
if self.start_node is not None:
# single node
if self.start_node.next is self.start_node:
self.start_node = None
else:
temp = self.start_node
while temp.next.next is not self.start_node:
temp = temp.next
temp.next= self.start_node
s2 = CSLL()
for i in range(50,0,-10):
s2.insert_last(i)
s2.display()
s2.delete_last()
s2.display()
output
50 40 30 20 10
50 40 30 20
delete a node at beginning
class CSLL:
def __init__(self):
self.start_node = None
def insert_last(self, value):
new_node = Node(value) # create new node
# empty list case
if self.start_node is None:
self.start_node = new_node
self.start_node.next = self.start_node
else: # non_empty list
temp = self.start_node
while temp.next is not self.start_node:
temp = temp.next
# insert the node here
new_node.next = self.start_node
temp.next = new_node
def display(self):
# non empty list
if self.start_node is not None:
temp = self.start_node
while temp.next is not self.start_node:
print(temp.data, end=' ')
temp = temp.next
print(temp.data)
def delete_first(self):
# non empty list
if self.start_node is not None:
# single node
if self.start_node.next is self.start_node:
self.start_node = None
else: # multiple nodes case
temp = self.start_node
while temp.next is not self.start_node:
temp = temp.next
temp.next = self.start_node.next
self.start_node = self.start_node.next
s3 = CSLL()
for i in range(50,100,10):
s3.insert_last(i)
s3.display()
s3.delete_first()
s3.display()
output
50 60 70 80 90
60 70 80 90
10. Write a Python program to Insert a node at the beginning and
end and to delete a node at the beginning and end of doubly
linked list.
Insert a node at the beginning
A) class Node:
def __init__(self, value):
self.data = value
self.next = None
self.prev = None
Insert first & display
class GDLL:
def __init__(self):
self.start_node = None
def insert_first(self, new_value):
# create the node
new_node = Node(new_value)
# empty list
if self.start_node is None:
self.start_node = new_node
return
# non-empty list
new_node.next = self.start_node
self.start_node.prev = new_node
self.start_node = new_node
def disp(self):
temp = self.start_node
while temp is not None:
print(temp.data, end=' ')
temp=temp.next
s1 = GDLL()
for i in range(100,50,-10):
s1.insert_first(i)
s1.disp()
output
60 70 80 90 100
Insert a node at the end

1. #Represent a node of doubly linked list


2. class Node:
3. def __init__(self,data):
4. self.data = data;
5. self.previous = None;
6. self.next = None;
7.
8. class InsertEnd:
9. #Represent the head and tail of the doubly linked list
10. def __init__(self):
11. self.head = None;
12. self.tail = None;
13.
14. #addAtEnd() will add a node to the end of the list
15. def addAtEnd(self, data):
16. #Create a new node
17. newNode = Node(data);
18.
19. #If list is empty
20. if(self.head == None):
21. #Both head and tail will point to newNode
22. self.head = self.tail = newNode;
23. #head's previous will point to None
24. self.head.previous = None;
25. #tail's next will point to None, as it is the last node of th
e list
26. self.tail.next = None;
27. #Add newNode as new tail of the list
28. else:
29. #newNode will be added after tail such that tail's next w
ill point to newNode
30. self.tail.next = newNode;
31. #newNode's previous will point to tail
32. newNode.previous = self.tail;
33. #newNode will become new tail
34. self.tail = newNode;
35. #As it is last node, tail's next will point to None
36. self.tail.next = None;
37.
38. #display() will print out the nodes of the list
39. def display(self):
40. #Node current will point to head
41. current = self.head;
42. if(self.head == None):
43. print("List is empty");
44. return;
45. print("Adding a node to the end of the list: ");
46. while(current != None):
47. #Prints each node by incrementing pointer.
48. print(current.data),
49. current = current.next;
50.
51. print();
52.
53. dList = InsertEnd();
54.
55. #Adding 1 to the list
56. dList.addAtEnd(1);
57. dList.display();
58. #Adding 2 to the list
59. dList.addAtEnd(2);
60. dList.display();
61. #Adding 3 to the list
62. dList.addAtEnd(3);
63. dList.display();
64. #Adding 4 to the list
65. dList.addAtEnd(4);
66. dList.display();
67. #Adding 5 to the list
68. dList.addAtEnd(5);
69. dList.display();

Output:

Adding a node to the end of the list:


1
Adding a node to the end of the list:
12
Adding a node to the end of the list:
123
Adding a node to the end of the list:
1234
Adding a node to the end of the list:
1 2 3 4 5
1.delete a node at the beginning
2. #Represent a node of doubly linked list
3. class Node:
4. def __init__(self,data):
5. self.data = data;
6. self.previous = None;
7. self.next = None;
8.
9. class DeleteStart:
10. #Represent the head and tail of the doubly linked list
11. def __init__(self):
12. self.head = None;
13. self.tail = None;
14.
15. #addNode() will add a node to the list
16. def addNode(self, data):
17. #Create a new node
18. newNode = Node(data);
19.
20. #If list is empty
21. if(self.head == None):
22. #Both head and tail will point to newNode
23. self.head = self.tail = newNode;
24. #head's previous will point to None
25. self.head.previous = None;
26. #tail's next will point to None, as it is the last node of the list
27. self.tail.next = None;
28. else:
29. #newNode will be added after tail such that tail's next will point to newN
ode
30. self.tail.next = newNode;
31. #newNode's previous will point to tail
32. newNode.previous = self.tail;
33. #newNode will become new tail
34. self.tail = newNode;
35. #As it is last node, tail's next will point to None
36. self.tail.next = None;
37.
38. #deleteFromStart() will delete a node from the beginning of the list
39. def deleteFromStart(self):
40. #Checks whether list is empty
41. if(self.head == None):
42. return;
43. else:
44. #Checks whether the list contains only one element
45. if(self.head != self.tail):
46. #head will point to next node in the list
47. self.head = self.head.next;
48. #Previous node to current head will be made None
49. self.head.previous = None;
50.
51. #If the list contains only one element
52. #then, it will remove the node, and now both head and tail will point to
None
53.
54. else:
55. self.head = self.tail = None;
56.
57. #display() will print out the nodes of the list
58. def display(self):
59. #Node current will point to head
60. current = self.head;
61. if(self.head == None):
62. print("List is empty");
63. return;
64. while(current != None):
65. #Prints each node by incrementing pointer.
66. print(current.data),
67. current = current.next;
68. print();
69.
70. dList = DeleteStart();
71. #Add nodes to the list
72. dList.addNode(1);
73. dList.addNode(2);
74. dList.addNode(3);
75. dList.addNode(4);
76. dList.addNode(5);
77.
78. #Printing original list
79. print("Original List: ");
80. dList.display();
81. while(dList.head != None):
82. dList.deleteFromStart();
83. #Printing updated list
84. print("Updated List: ");
85. dList.display();

Output:

Original List:
1 2 3 4 5
Updated List:
2 3 4 5
Updated List:
3 4 5
Updated List:
4 5
Updated List:
5
Updated List:
List is empty

delete a node at the end


class GDLL:
def __init__(self):
self.start_node = None
def insert_first(self, new_value):
# create the node
new_node = Node(new_value)
# empty list
if self.start_node is None:
self.start_node = new_node
return
# non-empty list
new_node.next = self.start_node
self.start_node.prev = new_node
self.start_node = new_node
def disp(self):
temp = self.start_node
while temp is not None:
print(temp.data, end=' ')
temp=temp.next
def del_last(self):
# non-empty list
if self.start_node is not None:
# single node
if self.start_node.next is None:
self.start_node=None
return
# multiple nodes
temp=self.start_node
# traverse upto last but one node
while temp.next.next is not None:
temp = temp.next
# last node prev pointer
temp.next.prev = None
temp.next = None
s2 = GDLL()
for i in range(100,50,-10):
s2.insert_first(i)
s2.disp()
s2.del_last()
s2.disp()
output
60 70 80 90 100
60 70 80 90

11. a) Differences between Linear and Binary search.


b) Differences between Doubly and Circular Linked Lists.
A)
Basis of Linear search Binary search
comparison

Definition The linear search starts searching from It finds the position of the searched
the first element and compares each element by finding the middle element
element with a searched element till the of the array.
element is not found.
Sorted data In a linear search, the elements don't The pre-condition for the binary search
need to be arranged in sorted order. is that the elements must be arranged
in a sorted order.

Implementation The linear search can be implemented The implementation of binary search is
on any linear data structure such as an limited as it can be implemented only
array, linked list, etc. on those data structures that have
two-way traversal.

Approach It is based on the sequential approach. It is based on the divide and conquer
approach.

Size It is preferrable for the small-sized data It is preferrable for the large-size data
sets. sets.

Efficiency It is less efficient in the case of large-size It is more efficient in the case of large-
data sets. size data sets.

Worst-case In a linear search, the worst- case In a binary search, the worst-case
scenario scenario for finding the element is O(n). scenario for finding the element is
O(log2n).

Best-case In a linear search, the best-case scenario In a binary search, the best-case
scenario for finding the first element in the list is scenario for finding the first element in
O(1). the list is O(1).

Dimensional It can be implemented on both a single It can be implemented only on a


array and multidimensional array. multidimensional array.

Doubly Linked List (DLL)

Doubly linked list is a sequence of elements in which every element has


links to its previous element and next element in the sequence.
In double linked list, every node has link to its previous node and next
node. So, we can traverse forward by using next field and can traverse
backward by using previous field. Every node in a double linked list
contains three fields and they are shown in the following figure...

Here, 'link1' field is used to store the address of the previous node in
the sequence, 'link2' field is used to store the address of the next
node in the sequence and 'data' field is used to store the actual value
of that node.
Example:
Circular Linked List (CLL)

Circular linked list is a sequence of elements in which every element has


link to its next element in the sequence and the last element has a link to
the first element in the sequence.

Example:

Circular list has no end.


In a circular linked list there are two methods to know if a node is the first
node or not.

 Either a external pointer, list, points the first node or


 A header node is placed as the first node of the circular list.

12. Perform bubble sort on these numbers( 10,2,4,8,5,12,11) and


write a program for the bubble sort
A)
def bubble_sort(lst):
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 = [ 10,2,4,8,5,12,11]
bubble_sort(l)
[2, 4, 5, 8, 10, 11, 12]
def bubble_sort(lst):
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

13. Perform bubble sort on these numbers( 20,13,6,8,1,19,3) and


write a program for the Insertion sort
A)
def bubble_sort(lst):
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 = [ 20,13,6,8,1,19,3]
bubble_sort(l)
output:
[1, 3, 6, 8, 13, 19, 20]
a program for the Insertion sort
def insert_sort(lst):
n = len(lst)
for i in range(1, n):
key = lst[i] # element to be inserted
j = i-1
while j>=0 and key < lst[j]:
lst[j+1] = lst[j] # jth element push it down
j -= 1
lst[j+1] = key # insert the key in the free slot
return lst

14. Perform bubble sort on these numbers(9,3,7,12,8,11,15) and


write a program for the Selection sort.
A)
def bubble_sort(lst):
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.

You might also like