Python - C style Linked List implementation

190 Views Asked by At

I have the following code, and I'm trying to implement insert function(without any OOP technique). The output coming was 1. Which basically means that the variable root was not passed as a reference. Is there any specific way, I can do that?? Secondly, I can implement it using a separate linked list class, in that case my root node will be unique for every linked list class object, and I won't have this problem of root being mishandled.

Can you please suggest, how can I implement it in the following way:-

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

def insert(root, data):
    temp = root
    root = Node(data)
    root.next = temp

root = Node(1)
insert(root, 2)
print(root.data)

whereas, then I implemented the following code, obviously it is working, but I want the above code to work:-

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


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

    def insert(self, data):
        temp = self.root
        self.root = Node(data)
        self.root.next = temp

ll = LinkedList()
ll.insert(5)
ll.insert(6)
print(ll.root.data)
2

There are 2 best solutions below

2
On BEST ANSWER

Assigning to root will not modify the object that root points to, but you can still modify the properties of root:

def insert(root, data):
    # Clone the old root
    old_root = Node(root.data)
    old_root.next = root.next

    # Overwrite with the "new" root and link the old one
    root.data = data
    root.next = old_root
2
On

The easiest way to do is to let insert() return the new root as

def insert(root, data):
    temp = root
    root = Node(data)
    root.next = temp

    # Now we return the new root.
    return root

Test

>>> root = Node(1)

>>> # the root is updated with the new object returned by the insert
>>> root = insert(root, 2)

>>> #This will return the new root.data
>>> print(root.data)
2