Skip to content Skip to sidebar Skip to footer

How Do Create A Linked List In Python

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(ob

Solution 1:

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 nodetail = tail.next # Move the tail pointer

Solution 2:

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

Solution 3:

You can add a next argument to the constructor:

classListNode(object):
    def__init__(self, x, next=None):
        self.x = x
        self.next = next

head = Nonefor x in [5, 1, 7, 96]:
    head = ListNode(x, next=head)

# Linked list looks like:# (96) -> ( 7) -> ( 1) -> ( 5) -> None

Post a Comment for "How Do Create A Linked List In Python"