Search code examples
pythonlinked-listsingly-linked-list

Python : I am not able to prepend a Value in a Singly Linked list


Code written in python:

prepend Function is supposed to add a value to the start of the Linked List display Function is supposed to display the linked list in a List format in python fromarr Function is supposed to add new nodes to the linked list

class Node:
    def __init__(self,value=None):
        self.value = value
        self.next = None
    
class SinglyLL:
    def __init__(self):
        self.head = Node()
        self.tail = Node()
    def prepend(self,value):
        newnode  = Node(value)
        newnode.next = self.head
        self.head = newnode
    def append(self,data):
        newnode = Node(data)
        if self.head is None:
            self.head = newnode
            return
        cur = self.head
        while cur.next != None:
            cur = cur.next
        cur.next = newnode
        newnode.next = None
    def display(self):
        lis = []
        cur = self.head
        while cur.next != None:
            cur = cur.next
            lis.append(cur.value)
        return lis
    def fromarr(self,list):
        for i in list:
            temp = Node(i)
            self.append(temp.value)

newsll = SinglyLL()
newsll.fromarr([1,2,3,4,5])
newsll.prepend(10)
print(newsll.display())

Expected output : [10,1,2,3,4,5]

Actual Output: [None,1,2,3,4,5]


Solution

  • well you are initalising your head with a empty node, and displaying values from self.head.next, so instead of setting element at position 0 you need to set element at position 1.

    Adding below code for prepend method

    class Node:
        def __init__(self,value=None):
            self.value = value
            self.next = None
    
    class SinglyLL:
        def __init__(self):
            self.head = Node()
            self.tail = Node()
        def prepend(self,value):
            newnode  = Node(value)
            if self.head is None:
                self.head = newnode
            else:
                tmp = self.head.next
                self.head.next = newnode
                newnode.next = tmp
    
        def append(self,data):
            newnode = Node(data)
            if self.head is None:
                self.head = newnode
                return
            cur = self.head
            while cur.next != None:
                cur = cur.next
            cur.next = newnode
            newnode.next = None
        def display(self):
            lis = []
            cur = self.head
            while cur.next != None:
                cur = cur.next
                lis.append(cur.value)
            return lis
        def fromarr(self,list):
            for i in list:
                temp = Node(i)
                self.append(temp.value)
    
    newsll = SinglyLL()
    newsll.fromarr([1,2,3,4,5])
    newsll.prepend(10)
    print(newsll.display())