0% found this document useful (0 votes)
2 views22 pages

DSA Lab 7

The document is a lab report detailing the development of a Python program for deleting nodes from a singly linked list. It covers objectives, required equipment, procedures, algorithms for deletion at various positions, and includes multiple Python code examples for implementing these operations. Additionally, it outlines lab tasks related to linked list manipulations, such as removing occurrences of a specific element and merging two sorted linked lists.

Uploaded by

amjidprogrammer
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)
2 views22 pages

DSA Lab 7

The document is a lab report detailing the development of a Python program for deleting nodes from a singly linked list. It covers objectives, required equipment, procedures, algorithms for deletion at various positions, and includes multiple Python code examples for implementing these operations. Additionally, it outlines lab tasks related to linked list manipulations, such as removing occurrences of a specific element and merging two sorted linked lists.

Uploaded by

amjidprogrammer
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/ 22

UNIVERSITYOF ENGINEERING AND TECHNOLOGY

TAXILA

Submitted To:
Engr. Iqra Jabeen

Submitted By:
Amjid Khan (23-TE-86)

Subject:
Data Structure and Algorithms Lab

DEPARTMENT OF TELECOMMUNICATION
ENGINEERING
1

Lab Report: 7
Development of a Program in Python for Deletion from the Singly Linked
List

Objectives:
➢ Remove nodes from the start, middle, or end of a singly linked list.
➢ Handle special cases like an empty list or a single-node list.
➢ Ensure proper updating of links after deletion.
➢ Keep the deletion process efficient.
➢ Make the program simple and user-friendly.

Equipment Required:
➢ Computer/Laptop with at least 4 GB RAM.
➢ Python 3.x installed and configured.
➢ IDE/Text Editor like PyCharm, VS Code, or Jupyter, Notebook etc.
➢ NumPy library (optional) for advanced array handling.
➢ Internet connection for downloading resources and accessing documentation.

Procedure:
➢ Open Computer System.
➢ Go to all programs.
➢ Open python.
➢ Create a new file with the extension .py.
➢ Write all the required code and then run the module.

Introduction:
Deleting a node in a Linked List is an important operation and can be done in three main ways:
removing the first node, removing a node in the middle, or removing the last node. We need to
skip the desired number of nodes to reach the node after which the node will be deleted. This
requires traversing through the list.
2

Algorithm:
1. If the head node has the given key, Make the head node point to the second node and
free its memory.
2. Otherwise, from the current node, check whether the next node has the given key if yes,
make the current->next = current->next->next and free the memory.

Delete at the Beginning of the Linked List


Deleting a node from the beginning of the list is the simplest operation of all. It just needs a few
adjustments in the node pointers. Since the first node of the list is to be deleted, we just need to
make the head, point to the next head.

Algorithm:
Step 1: IF HEAD = NULL
Write UNDERFLOW
Go to Step 5
[END OF IF]
Step 2: SET PTR = HEAD
Step 3: SET HEAD = HEAD -> NEXT
Step 4: FREE PTR
Step 5: EXIT
3

Python code:
def atstart(self):
temp = self.head
self.head = temp.next
temp.next = None

Delete the Middle Node of the Linked List


1. Make the current node point to the head node. (current → data = 10).
2. Current → next. (current→next→data = 20).
3. Current → next → next. (current→next→next→data = 30).
4. We must remove the node 20. Since current →next = 20 we can remove the node by
setting current →next = current→>next → next. And then free the node.
5. Finally, the new linked list.
4

Python code:
def atspecificposition(self, pos):
prev = self.head
temp = self.head.next
for i in range(1, pos - 1):
temp = temp.next
prev = prev.next
prev.next = temp.next

Delete the Last Node of the linked list


To perform the deletion at the end of the Linked List, we must traverse the list to find the second
last node, and then set its next pointer to null. If the list is empty, then there is no node to delete
or only one node, pointing the head to null.
1. Deleting the last node is like deleting from any other index. The difference holds in the
limit of the while loop. Here we run a loop until the pointer reaches the end and points to
NULL.
2. Assign NULL to the next member of the p structure using ptr→ next = NULL.
3. Break the connection between q and NULL by freeing the ptr .q.
4. Return head.

def attend(self):
prev = self.head
temp = self.head.next
while temp.next is not None:
temp = temp.next
prev = prev.next
prev.next = None
5

Method:1
Deleting a node from the beginning of the list is the simplest operation of all. It just needs a few
adjustments in the node pointers. Since the first node of the list is to be deleted, we just need to
make the head, point to the next of the head. This will be done by using the following statements.
Given a linked list, the task is to remove the first node from the given linked list.

Python code:
class Node:
def __init__(self, data):
self.data = data
self.next = None

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

def display(self):
if self.head is None:
print("linked list is empty")
else:
temp = self.head
while temp:
print(temp.data, "-->", end="")
temp = temp.next
6

def delete_beginning(self):
temp = self.head
self.head = temp.next
temp.next = None

L = singlelinkedlist()
n = Node(10)
L.head = n
n1 = Node(20)
n.next = n1
n2 = Node(30)
n1.next = n2
n3 = Node(40)
n2.next = n3
L.delete_beginning()
L.display()

Output:

Code: 2
class Node:
def __init__(self, data):
self.data = data
self.next = None
class SingleLinkedList:
def __init__(self):
self.head = None
7

def display(self):
if self.head is None:
print("Linked list is empty")
else:
temp = self.head
while temp:
print(temp.data, "-->", end="")
temp = temp.next
print("None")
def at_start(self):
if self.head is None:
print("The list is empty, nothing to
remove")
else:
temp = self.head
self.head = temp.next
temp.next = None
print(f"Removed the node with data:
{temp.data}")
AB = SingleLinkedList()
n = Node(10)
AB.head = n
n1 = Node(20)
n.next = n1
n2 = Node(30)
n1.next = n2
n3 = Node(40)
n2.next = n3
AB.at_start()
AB.display()
8

Output:

Code: 3
class Node:
def __init__(self, data):
self.data = data
self.next = None
class SingleLinkedList:
def __init__(self):
self.head = None
def display(self):
if self.head is None:
print("Linked list is empty")
else:
temp = self.head
while temp:
print(temp.data, "-->", end="")
temp = temp.next
print("None")
def at_start(self):
if self.head is None:
print("The list is empty, nothing to
remove")
else:
temp = self.head
self.head = temp.next
temp.next = None
9

print(f"Removed node at the start with data:


{temp.data}")
def at_end(self):
if self.head is None:
print("The list is empty, nothing to
remove")
elif self.head.next is None:
# Only one element in the list
print(f"Removed the last node with data:
{self.head.data}")
self.head = None
else:
prev = self.head
temp = self.head.next
while temp.next is not None:
prev = prev.next
temp = temp.next
prev.next = None
print(f"Removed node at the end with data:
{temp.data}")
def at_specific_position(self, pos):
if self.head is None:
print("The list is empty, nothing to
remove")
return
if pos == 1:
self.at_start()
return
prev = self.head
temp = self.head.next
for i in range(1, pos - 1):
if temp is None:
10

print("Position is out of range")


return
prev = prev.next
temp = temp.next
if temp is None:
print("Position is out of range")
return
prev.next = temp.next
print(f"Removed node at position {pos} with
data: {temp.data}")
temp.next = None
AB = SingleLinkedList()
n = Node(10)
AB.head = n
n1 = Node(20)
n.next = n1
n2 = Node(30)
n1.next = n2
n3 = Node(40)
n2.next = n3
AB.at_specific_position(3)
AB.display()

Output:
11

Lab Tasks:
1. Write a Python code that removes all occurrences of a specific element from a linked list and
generates the following output.

Original List:

1→3→3→3→4

List after removing all occurrences of 3:

1→4

class Node:
def __init__(self, data):
self.data = data
self.next = None
class SingleLinkedList:
def __init__(self):
self.head = None
def display(self):
if self.head is None:
print("Linked list is empty")
else:
temp = self.head
while temp:
print(temp.data, end=" --> " if
temp.next else "")
temp = temp.next
print()
def remove_occurrences(self, value):
while self.head is not None and self.head.data
== value:
self.head = self.head.next
current = self.head
12

while current is not None and current.next is


not None:
if current.next.data == value:
current.next = current.next.next
else:
current = current.next
llist = SingleLinkedList()
llist.head = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(3)
n5 = Node(4)
llist.head.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
print("Original List:")
llist.display()
llist.remove_occurrences(3)
print("List after removing all occurrences of 3:")
llist.display()

Output:

2. Write a Python code that takes two sorted linked lists and merges them into a single
sorted linked list.
List:1
1→4→10→11
13

List:2
1→2→3→6
Merged List
1→1→2→3→4→6→10→11

class Node:
def __init__(self, data):
self.data = data
self.next = None
class SingleLinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
temp = self.head
while temp.next:
temp = temp.next
temp.next = new_node
def display(self):
temp = self.head
while temp:
print(temp.data, end=" → " if temp.next else
"")
temp = temp.next
print()
def merge_sorted_lists(list1, list2):
dummy = Node(0)
tail = dummy
l1, l2 = list1.head, list2.head
14

while l1 and l2:


if l1.data <= l2.data:
tail.next = l1
l1 = l1.next
else:
tail.next = l2
l2 = l2.next
tail = tail.next
if l1:
tail.next = l1
if l2:
tail.next = l2
merged_list = SingleLinkedList()
merged_list.head = dummy.next
return merged_list
list1 = SingleLinkedList()
list2 = SingleLinkedList()
list1.append(1)
list1.append(4)
list1.append(10)
list1.append(11)
list2.append(1)
list2.append(2)
list2.append(3)
list2.append(6)
print("List 1:")
list1.display()
print("List 2:")
list2.display()
merged_list = merge_sorted_lists(list1, list2)
print("Merged List:")
merged_list.display()
15

Output:

3. Write a Python code that swaps nodes in a linked list without swapping data and
generates the following output by swapping node x with node y.
Input:
2→3→4→5→6→7
Output:
2→3→6→5→4→7

class Node:
def __init__(self, data):
self.data = data
self.next = None
class SingleLinkedList:
def __init__(self):
self.head = None
def display(self):
if self.head is None:
print("Linked list is empty")
else:
temp = self.head
while temp:
print(temp.data, end=" --> " if
temp.next else "")
temp = temp.next
print()
def swap_nodes(self, x, y):
16

if x == y:
return
prevX = None
currX = self.head
while currX and currX.data != x:
prevX = currX
currX = currX.next
prevY = None
currY = self.head
while currY and currY.data != y:
prevY = currY
currY = currY.next
if not currX or not currY:
print(f"Either {x} or {y} is not present in
the list.")
return
if prevX:
prevX.next = currY
else:
self.head = currY
if prevY:
prevY.next = currX
else:
self.head = currX
temp = currX.next
currX.next = currY.next
currY.next = temp
llist = SingleLinkedList()
llist.head = Node(2)
n2 = Node(3)
n3 = Node(4)
n4 = Node(5)
17

n5 = Node(6)
n6 = Node(7)
llist.head.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
n5.next = n6
print("Original List:")
llist.display()
llist.swap_nodes(4, 6)
print("List after swapping nodes 4 and 6:")
llist.display()

Output:

4. Write a Python code and generate the following output.


Input:
2→2→2→2→6→6
Output:
Empty List

class Node:
def __init__(self, data):
self.data = data
self.next = None
class SingleLinkedList:
def __init__(self):
18

self.head = None
def display(self):
if self.head is None:
print("Empty List")
else:
temp = self.head
while temp:
print(temp.data, end=" → " if temp.next
else "")
temp = temp.next
print()
def remove_occurrences(self, value):
while self.head is not None and self.head.data
== value:
self.head = self.head.next
current = self.head
while current is not None and current.next is
not None:
if current.next.data == value:
current.next = current.next.next
else:
current = current.next
def remove_all(self):
self.head = None
llist = SingleLinkedList()
llist.head = Node(2)
n2 = Node(2)
n3 = Node(2)
n4 = Node(2)
n5 = Node(6)
n6 = Node(6)
llist.head.next = n2
19

n2.next = n3
n3.next = n4
n4.next = n5
n5.next = n6
print("Original List:")
llist.display()
llist.remove_occurrences(2)
llist.remove_occurrences(6)
if llist.head is None:
print("List after removing all occurrences:")
llist.display()
else:
print("List is not empty.")

Output:

5. Write a Python code and generate the following output.


List before removal of duplicates
20 23 23 34 35 35 50 50
List After removal of duplicates
23 35

class Node:
def __init__(self, data):
self.data = data
self.next = None
class SingleLinkedList:
20

def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
temp = self.head
while temp.next:
temp = temp.next
temp.next = new_node
def display(self):
temp = self.head
while temp:
print(temp.data, end=" " if temp.next else
"")
temp = temp.next
print()
def remove_all_duplicates(self):
if self.head is None:
return
freq = {}
current = self.head
while current:
if current.data in freq:
freq[current.data] += 1
else:
freq[current.data] = 1
current = current.next
dummy = Node(0)
dummy.next = self.head
prev = dummy
21

current = self.head
while current:
if freq[current.data] > 1:
prev.next = current.next
else:
prev = current
current = current.next
self.head = dummy.next
llist = SingleLinkedList()
llist.append(20)
llist.append(23)
llist.append(23)
llist.append(34)
llist.append(35)
llist.append(35)
llist.append(50)
llist.append(50)
print("List before removal of duplicates:")
llist.display()
llist.remove_all_duplicates()
print("List after removal of duplicates:")
llist.display()

Output:

You might also like