首页 > 解决方案 > 链接列表:打印列表时 Sublime 文本崩溃

问题描述

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

class LinkedList:
    def __init__(self):
        self.head=None
    def printList(self):
        temp=self.head
        while(temp):
            print(int(self.head.data))
            temp=self.head.next
    def insertEnd(self,data):
        newnode=Node(data)

        if self.head is None:
            
            self.head=newnode
        else:
            last=self.head
            while(last.next):
                last=last.next
            
            last.next=newnode

    def delEnd(self):
        if self.head is None:
            print("Empty")
        else:
            last=self.head
            while(last.next):
                last=last.next
            print(last.data)
            del last
lst=LinkedList()
while(1):
    choice=int(input("1:To Insert at end \n2:To delete at end \n3:To print list"))
    if choice==1:
        value=int(input("Enter the value: "))
        lst.insertEnd(value)
    elif choice==2:
        lst.delEnd()
    elif choice==3:
        lst.printList()

标签: pythonpython-3.xlinked-list

解决方案


在你的循环中printList,你不temp应该在你应该使用的时候使用:

    while(temp):
        print(int(self.head.data))
        temp=self.head.next

如果列表有两个以上的节点,则此循环将永远运行,因为temp总是会self.head.next一遍又一遍地设置。

你要:

    while temp:
        print(int(temp.data))
        temp = temp.next

推荐阅读