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)
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With