Paul Lee
Paul Lee

Reputation: 13

python linked list evaluation on the node of self

I built two linked lists, but I lost the link by the second function. I can see that I got None to self, but how could it lose the link from its parent. Because None is an independent memory address?

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

    def buildLink1(self):
        temp=1
        while temp<10:
            self.next=Node(temp)
            self=self.next
            temp+=1

    def buildLink2(self):
        temp=1
        while temp<10:
            self=self.next
            self=Node(temp)
            temp+=1

    def traverse(self):
        while self:
            print self.data
            self=self.next

if __name__=='__main__':
    print "link 1:"
    root1=Node(10)
    root1.buildLink1()
    root1.traverse()
    print "link 2:"
    root2=Node(10)
    root2.buildLink2()
    root2.traverse()

output: link 1: 10 1 2 3 4 5 6 7 8 9 link 2: 10

Upvotes: 1

Views: 448

Answers (1)

tacaswell
tacaswell

Reputation: 87496

The issue is in the sections like this.

def buildLink2(self):
    temp=1
    while temp<10:
        self=self.next
        self=Node(temp)
        temp+=1

self is a reference to the current object, but it is not special (other than by convention), and when you assign to it python makes it a local variable.

So what is happening here, is you set self to be a reference to what ever self.next references (which is this case is None), and then you set self to point at a new Node object. The next time through the loop, you point self at None again before you do anything.

I think you really don't want these functions to be instance methods, but to be either class methods or stand-alone methods. eg:

def build_link(first_node):

    cur_node = first_node
    for tmp in range(10):
        cur_node.next = Node(tmp)
        cur_node = cur_node.next

Upvotes: 3

Related Questions