0% found this document useful (0 votes)
7 views2 pages

Linked List Operations in Python

This document contains a Python program for creating and manipulating a singly linked list. It includes functions for accepting node data, creating the list, inserting nodes at the beginning, end, and after a specified node, and traversing the list to display its contents. The program prompts the user for input to build and modify the linked list interactively.
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)
7 views2 pages

Linked List Operations in Python

This document contains a Python program for creating and manipulating a singly linked list. It includes functions for accepting node data, creating the list, inserting nodes at the beginning, end, and after a specified node, and traversing the list to display its contents. The program prompts the user for input to build and modify the linked list interactively.
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/ 2

# Python Program for traversal of Singly Linked list

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

def accept_node():
data = int(input("Enter data: "))
return Node(data)

def create():

head = None
n = int(input("Enter number of nodes in LL: "))

for i in range(n):
temp = accept_node()
if head is None:
head = temp
else:
nl = head
while nl.next is not None:
nl = nl.next
nl.next = temp
return head

def insert_at_beginning(head):

new_node = accept_node()

new_node.next = head
return new_node

def insert_at_end(head):

new_node = accept_node()

if head is None:
return new_node

temp = head
while temp.next:
temp = temp.next

temp.next = new_node
return head

def insert_after_node(head, n):

temp = accept_node()

n1 = head
while n1 is not None and n1.data != n:
n1 = n1.next

if n1 is not None:
temp.next = n1.next
n1.next = temp
else:
print(f"Node with value {n} not found.")

return head

def traverse(head):
temp = head
while temp:
print(str(temp.data) + " -> ", end=" ")
temp = temp.next
print("None")

head = create()

traverse(head)

print("New node at beginning")


head = insert_at_beginning(head)
traverse(head)

print("New node at end")


head = insert_at_end(head)
traverse(head)

print("New node after a node")


n = int(input("enter node value after which new node to be inserted "))
head = insert_after_node(head,n)
traverse(head)

You might also like