Python Program For Inserting A Node In A Linked List

Python Program For Inserting A Node In A Linked List

Creating a simple linked list and then inserting a node at various positions.

Here's a simple Python program for inserting a node in a linked list:

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 insert_after_node(self, prev_node, data): if not prev_node: print("Previous node is not in the list") return new_node = Node(data) new_node.next = prev_node.next prev_node.next = new_node def prepend(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node def print_list(self): cur_node = self.head while cur_node: print(cur_node.data, end=" -> ") cur_node = cur_node.next print("None") # Driver code llist = LinkedList() llist.append("A") llist.append("B") llist.append("D") # Missing C on purpose llist.print_list() # Inserting C after B llist.insert_after_node(llist.head.next, "C") print("After inserting C:") llist.print_list() # Prepending E at the beginning llist.prepend("E") print("After prepending E:") llist.print_list() 

The LinkedList class contains methods:

  • append(): For adding a node at the end of the list.
  • prepend(): For adding a node at the beginning of the list.
  • insert_after_node(): For adding a node after a given node.

The print_list() method is just for visually verifying our operations.


More Tags

ubuntu comparison-operators ionicons common-dialog findbugs android-xml multiple-file-upload language-theory bundle space-analysis

More Programming Guides

Other Guides

More Programming Examples