insert method for linked list in python

To insert a node in a linked list, we need to perform the following steps:

  1. Create a new node with the given value.
  2. If the linked list is empty, then make the new node as the head and return.
  3. Traverse the linked list until we reach the position where the node should be inserted.
  4. Insert the new node by updating the pointers of its previous and next nodes.

Here is the implementation of an insert method for a singly-linked list in Python:

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

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

    def insert(self, data, position=None):
        new_node = Node(data)

        if position is None:
            if self.head is None:
                self.head = new_node
            else:
                curr_node = self.head
                while curr_node.next is not None:
                    curr_node = curr_node.next
                curr_node.next = new_node
        else:
            if position == 0:
                new_node.next = self.head
                self.head = new_node
            else:
                prev_node = None
                curr_node = self.head
                for i in range(position):
                    prev_node = curr_node
                    curr_node = curr_node.next
                    if curr_node is None:
                        break
                new_node.next = curr_node
                prev_node.next = new_node
1029 chars
35 lines

This implementation allows you to insert a new node at the end of the linked list or at a specific position indicated by the position parameter. If the position parameter is not provided, it inserts the new node at the end. If the position parameter is equal to 0, it inserts the new node at the head of the linked list.

gistlibby LogSnag