Search code examples
pythonloopslinked-listtraversal

traverse listnode in python


Can someone help me with how can I traverse through below given listnode in python. I have written this command and am getting such outputs.

list1=[1,2,4]

Command:-

print(list1)
print(list1.val)
print(list1.next.val)

OUTPUT:-

ListNode{val: 1, next: ListNode{val: 2, next: ListNode{val: 4, next: None}}}
1
2

Solution

  • To get the output you have listed at the end of your question, you would need to create a linked list. For instance, if you define the following class:

    class ListNode:
        def __init__(self, val, nxt=None):
            self.val = val
            self.next = nxt
    
        def __repr__(self):
            return f"ListNode{{val: {self.val}, next: {self.next}}}"
    

    And if you then define list1 as follows:

    list1 = ListNode(1, ListNode(2, ListNode(4, None)))
    

    Then the "commands" will give the output that you listed.

    List to Linked List

    If you want to create the above linked list from the list [1,2,4], then use this function:

    def createLinkedList(values):
        head = None
        for val in reversed(values):
            head = ListNode(val, head)
        return head
    

    Now you can convert a plain list to a linked list as follows:

    list1 = createLinkedList([1,2,4])
    

    Linked List to list

    If you want to do the opposite, and create a standard list from a linked list, then define this function:

    def linkedListIterator(head):
        while head:
            yield head.val
            head = head.next
    

    Now, if you have a linked list, you can pass it to the above function. For instance:

    list1 = createLinkedList([1,2,4])
    lst = list(linkedListIterator(list1))
    

    lst will be [1,2,4]