0% found this document useful (0 votes)
3 views1 page

Dss

The document defines a simple implementation of a singly linked list in Python, including methods for displaying the list and inserting a new node in the middle. It creates a linked list with three nodes and demonstrates the insertion of a new node with the value 15. The display method shows the list before and after the insertion.

Uploaded by

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

Dss

The document defines a simple implementation of a singly linked list in Python, including methods for displaying the list and inserting a new node in the middle. It creates a linked list with three nodes and demonstrates the insertion of a new node with the value 15. The display method shows the list before and after the insertion.

Uploaded by

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

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 is not None:
print(temp.data, "-->", end="")
temp = temp.next

def insert_in_middle(self, data):


if self.head is None:
print("Linked list is empty")
else:
slow_ptr = self.head
fast_ptr = self.head

while fast_ptr.next is not None and fast_ptr.next.next is not None:


slow_ptr = slow_ptr.next
fast_ptr = fast_ptr.next.next

new_node = Node(data)
new_node.next = slow_ptr.next
slow_ptr.next = new_node

L = SingleLinkedList()
n1 = Node(10)
n2 = Node(20)
n3 = Node(30)
L.head = n1
n1.next = n2
n2.next = n3
L.display()
L.insert_in_middle(15)
L.display()

You might also like