'How to retrieve the first added node when a LinkedList is created?
I have created a linkedlist in Python using below classes:
class: Node
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
class LinkedList:
def __init__(self):
self.head = None
def insert_at_beginning(self, data):
temp = Node(data)
if self.head is None:
self.head = temp
else:
temp.next = self.head
self.head = temp
def insert_at_end(self, data):
temp = Node(data)
if self.head is None:
self.head = temp
else:
curr = self.head
while curr.next is not None:
curr = curr.next
curr.next = temp
def insert_at_position(self, pos, data):
temp = Node(data)
if self.head is None:
self.head = temp
else:
curr = self.head
i = 1
while i < pos:
curr = curr.next
i += 1
temp.next = curr.next
curr.next = temp
def traverse_list(self):
if self.head is None:
print('List is empty')
else:
curr = self.head
while curr.next is not None:
print(curr.data)
curr = curr.next
Below is the order I am calling the insertion methods.
ll = LinkedList()
ll.head = Node(1)
ll.insert_at_beginning(data=10)
ll.insert_at_beginning(data=11)
ll.traverse()
The elements printed in the output are: 11 & 10 which are the ones I inserted but I don't see the value 1 which is a node I added in the beginning.
Is there any logic I missed here that is making the first value skip or not being considered ?
Solution 1:[1]
Your problem comes from while curr.next is not None: in traverse_list(). Assuming you're pointing your last node, its next node is obviously None. Therefore, it will stop the loop before printing the last node's data.
You can try this:
def traverse_list(self):
if self.head is None:
print('List is empty')
else:
curr = self.head
while curr is not None:
print(curr.data)
curr = curr.next
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Minh Dao |
