Reputation: 2045
I see a linked list class definition in Leetcode:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = None
I am confused how to use it, there are two methods I want to figure out:
Firstly: if I want to create a linked list 1->3->5 step by step, how? My idea is that:
p1 = ListNode(1)
p2 = ListNode(3)
p3 = ListNode(5)
p2 = p1.next
p3 = p1.next.next
print(p1.val) #however it shows p1 doesn't have next attr...
Secondly, if I have a linked list, like that:
l1 = ListNode([1, 2, 4, 6])
How to get every value step by step? I tried like:
print(l3.next)
print(l3.next.next)#maybe just some false idea...
Upvotes: 2
Views: 406
Reputation: 545518
The constructor is wrong: it sets self.next
to None
rather than to next
. Let’s fix that:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
Now we can create a list of three nodes. Since this is a singly-linked forward list, we need start at the back:
p3 = ListNode(3)
p2 = ListNode(2, p3)
p1 = ListNode(1, p2)
print(p1.next.next.val) # 3
Or, to generate a linked list from a list:
def from_list(lst) -> ListNode:
node = None
for item in lst[::-1]:
node = ListNode(item, node)
return node
x = from_list([1, 2, 3, 4])
print(x.next.next.next.val) # 4
Upvotes: 2