打印链表节点

时间:2019-04-05 01:33:18

标签: python

我想先创建我的链表,然后打印列表列表节点。我尝试了几种方法,但始终得到错误的输出。

下面是我的代码:

sep

我当前的输出:

class node:
    def __init__(self, dataVal=None):
        self.dataVal = dataVal
        self.nextVal = None

class LinkedList:
    def __init__(self):
        self.headVal = None

    def printList(self):
        printVal = self.headVal
        while printVal is not None:
            print(printVal.dataVal)
            printVal = printVal.nextVal

    def insertEnd(self, n_node):
        new_node = node(n_node)
        if self.headVal is None:
            self.headVal = node(new_node)
        else:
            end = self.headVal
            while(end.nextVal):
                end = end.nextVal
            end.nextVal = new_node

def createList(array, n):
    linkedList = LinkedList()
    for i in range(n):
        linkedList.insertEnd(array[i])
    return linkedList

if __name__=='__main__':
    t = 2
    n = [5,6]
    array = [[1,2,3,4,5], [2,3,6,7,5,1]]
    for i in range(t):        
        head = createList(array[i], n[i])
        print(head.printList())

我的期望应该是:

<__main__.node object at 0x0000026152300400>
2
3
4
5
None
<__main__.node object at 0x00000261523257B8>
3
6
7
5
1
None

我不知道为什么显示“无”以及为什么也打印该对象。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

删除打印件以摆脱None。更改

print(head.printList())

head.printList()

if self.headVal is None:

等效但更多pythonic

if not self.headVal: