Reputation: 12940
I am trying to solve a linked list coding challenge in python. And I have given only following class to create a linked list
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
I can create a linked list something like this
x = ListNode(1)
x.next = ListNode(4)
x.next.next = ListNode(5)
however, How do I create iterativly (inside a for loop)
Upvotes: 4
Views: 17384
Reputation: 13
dummy = ListNode()
prev = dummy
for val in arr:
node = ListNode(val)
prev.next = node
prev = node
dummy.next
- is the link to the first element of created linked list
Upvotes: 1
Reputation: 57105
You need two "pointers" that memorize the head and the tail of your list. The head is initialized once. You will eventually use it to access the whole list. The tail changes every time you add another node:
data = [5, 1, 7, 96]
tail = head = ListNode(data[0])
for x in data[1:]:
tail.next = ListNode(x) # Create and add another node
tail = tail.next # Move the tail pointer
Upvotes: 3
Reputation: 4366
You can add a next
argument to the constructor:
class ListNode(object):
def __init__(self, x, next=None):
self.x = x
self.next = next
head = None
for x in [5, 1, 7, 96]:
head = ListNode(x, next=head)
# Linked list looks like:
# (96) -> ( 7) -> ( 1) -> ( 5) -> None
Upvotes: 0
Reputation: 2114
You can do something like:
arr = [1,4,5]
for i in arr:
x = ListNode(i)
x = x.next
But now x will become None
. As there's nothing else to keep track, you can't print the elements.
You can verify this by printing the values of x.val in between the loop:
arr = [1,4,5]
for i in arr:
x = ListNode(i)
print(x.val)
x = x.next
output:
1
4
5
Upvotes: 0