James Reid
James Reid

Reputation: 459

How to get the head node in linkedlist python

I've been trying to find a way to get the first data.

this is my data in database for example.

id    name     next
001   task1    002
002   task2    003
003   task3    000

what I want to do is to get the first value of the headnode which should be 001 as shown in the database.

this is my code

while True:
    self.headNode = 000
    try:
        lastNode = Task.objects.get(next=self.headNode)
        self.headNode = lastNode.id
        break
    except Task.DoesNotExist:
        break

What I expect here, the value of self.headNode should be 001 but it gave me 003. Please help me how to get that 001. I've been working on this for almost a month now.

this is the other data example.

id    name     next
222   task1    444
333   task2    222
444   task3    000

in here... the head node should be 333 and to know that. i will just get the data where the next is 000. Then get its so it is 444. then I will get the other data where the next is 444 and the id is 222. lastly get data were next is 222 then you will get the id 333. so that would show that the head node is 333. I hope I have explained it clearly.

Upvotes: 0

Views: 3344

Answers (1)

aliasav
aliasav

Reputation: 3168

The loop only runs once, since you have added a break statement.

Also, since the initial value of headNode in 000, lastNode will contain 003 since the query you have written, filters as next=000, which us the id 003. That's why you're getting 003

Okay, so if the headNode is a node that is not any other node's next, you can retrieve it this way:

self.headNode = 000
while True:    
    try:
        lastNode = Task.objects.get(next=self.headNode)
        self.headNode = lastNode.id        
    except Task.DoesNotExist:
        print("Head Node ->", self.headNode)
        break

Upvotes: 1

Related Questions