微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我的“链接列表”不能打印所有值?

如何解决为什么我的“链接列表”不能打印所有值?

我试图按以下顺序打印带有插入功能的链表: 约翰 本 马修

无论出于什么原因,即使我在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()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。