0

我正在尝试按以下顺序打印带有插入功能的链表:John Ben Matthew

无论出于何种原因,即使我在 printList() 函数中使用 while 循环,我也无法打印过去的“John”。

请在下面查看我的代码:

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

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

    def insert(self, newNode):
        if self.head is None:
            self.head = newNode
        else:
            lastNode = self.head
            while True:
                if lastNode.next is None:
                    break
                lastNode = lastNode.next
            lastNode.Next = newNode

    def printList(self):
        currentNode = self.head
        while True:
            if currentNode is None:
                break
            print(currentNode.data)
            currentNode = currentNode.next

firstNode = Node("John")
linkedList = LinkedList()
linkedList.insert(firstNode)
secondNode = Node("Ben")
linkedList.insert(secondNode)
thirdNode = Node("Matthew")
linkedList.insert(thirdNode)
linkedList.printList()
4

0 回答 0