How to print linked list items?

Today I am doing a Node exercise in python. I seem to have done some of this, but it is not a complete success.

class Node:
    def __init__(self, cargo=None, next=None):
        self.cargo = cargo
        self.next  = next

    def __str__(self):
        return str(self.cargo)

node1 = Node(1)
node2 = Node(2)
node3 = Node(3)

node1.next = node2
node2.next = node3

def printList(node):
  while node:
    print node,
    node = node.next
  print

So, this is the original __init__, __str__and printListthat does something like: 1 2 3.

I need to convert 1 2 3to [1,2,3].

I used appendin the list I created:

nodelist = []

node1.next = node2
node2.next = node3


def printList(node):
    while node:
        nodelist.append(str(node)), 
        node = node.next

But everything I get on my list is inside the line, and I don't want this.

If I exclude the conversion str, I only get memory space when I call the list with print. So, how can I get a list that has no limits?

+4
source share
2 answers

str() node cargo:

.
.
.    
while node:
    nodelist.append(node.cargo)
    node = node.next
.
.
.
+2
def printLinkedList(self):
    node = self.head
    while node != None:
        print(node.getData())
        node = node.getNext()
0

Source: https://habr.com/ru/post/1584995/


All Articles