Search code examples
pythondata-structureslinked-listsingly-linked-list

Inserting node at the beginning of a linked list - python implementation


I am trying to implement a method to the Linked_List class, which should insert a value at the beginning of the linked list. However the inserted value is None and I just can't see what am I missing? Any help will be appreciated!

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

    def display(self):
        elements = []
        cur_node = self.head
        while cur_node.next != None:
            cur_node = cur_node.next
            elements.append(cur_node.data)
        return elements

    def insertNodeAtBegining(self, value):
        new_node = Node(value)
        new_node.next = self.head
        self.head = new_node

Solution

  • insertion at beginning is right but your display method is wrong, the way you traversing a linked list is wrong, after checking curr_node.next is not None , you should take node value and add it to elements but you are forwarding to next node and adding that value, this skipping 0th element always.

    Below is code to traverse a linked list

    def display(self):
    
        curr_node = self.head
        elements = []
    
        if curr_node is None:
            return elements
    
        while curr_node:
             elements.append(curr_node.data)
             curr_node = curr_node.next
    
        return elements