Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

python - How to print the elements of a linked list?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of calling str() on the node, you should access it's cargo:

.
.
.    
while node:
    nodelist.append(node.cargo)
    node = node.next
.
.
.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...