Reputation: 89
I'm dong a Node exercise on python today. I seem to have accomplished a part of it, 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 that is the original __init__
, __str__
and printList
, which makes something like: 1 2 3
.
I have to transform 1 2 3
into [1,2,3]
.
I used append
on a 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 in my list is within a string, and I don't want that.
If I eliminate the str
conversion, I only get a memory space when I call the list with print
. So how do I get an unstringed list?
Upvotes: 6
Views: 10828
Reputation: 39
The code with getData did not work for me. I am able to print out the list values with:
visited_nodes = set()
current_node = head
while current_node:
print (current_node.val)
current_node = current_node.next
Upvotes: -1
Reputation: 2190
def printLinkedList(self):
node = self.head
while node != None:
print(node.getData())
node = node.getNext()
Upvotes: -1
Reputation: 4855
Instead of calling str()
on the node, you should access it's cargo
:
.
.
.
while node:
nodelist.append(node.cargo)
node = node.next
.
.
.
Upvotes: 2