Reputation: 399
I am trying to created a linked list. However, the following code keeps printing only the last element of the list. Is there an error in my code? I think the problem lies in the "insert" method. I am not able to figure out why though.
import sys
import io
string = """4
2
3
4
1"""
sys.stdin = io.StringIO(string)
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def display(self, head):
current = head
while current:
print(current.data, end=' ')
current = current.next
# TODO: Code only prints the last element of data
def insert(self, head, data):
if head == None:
head = Node(data)
return head
else:
head.next = Node(data)
return head.next
mylist = Solution()
T = int(input())
head = None
for i in range(T):
data = int(input())
head = mylist.insert(head, data)
mylist.display(head)
Upvotes: 0
Views: 109
Reputation: 2130
The problem is you're losing the reference to the head of the list. You must keep the head and insert the new item at the end of the list
def insert(self,head,data):
if head == None:
head = Node(data)
else:
current = head
while current.next != None:
current = current.next
current.next = Node(data)
return head
Upvotes: 4
Reputation: 1124718
You only keep a reference to the end of the chain (head.next
), so yes, you'll only be able to display that last element.
You'll need to keep a reference to the first element (the real head):
mylist = Solution()
T = int(input())
current = head = None
for i in range(T):
data = int(input())
current = mylist.insert(head, data)
if head is None:
head = current
Upvotes: 1