Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 950
Gaurang Shah Avatar asked Nov 01 '25 05:11

Gaurang Shah


2 Answers

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
like image 187
DYZ Avatar answered Nov 03 '25 19:11

DYZ


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

like image 43
maxim-lixakov Avatar answered Nov 03 '25 19:11

maxim-lixakov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!