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
CodePudding user response:
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]
CodePudding user response:
As mentioned in the comments, it appears as though you are confusing a list
with a singly linked list
.
With the list provided you would just iterate with a for loop
like this:
list1=[1,2,4]
for L in list1:
print(L)
Which gives the output:
1
2
4
For linked lists, please refer to this: https://www.tutorialspoint.com/python_data_structure/python_linked_lists.htm