LinkedList Python删除功能出现问题

时间:2020-05-02 19:30:43

标签: python

我正在用Python写一个简单的链表代码,您能告诉我deleteT函数出什么问题了吗?它没有做好自己的工作

class SinglyLLNode(object):
    def __init__(self,value):
        self.value = value
        self.next = None


class SinglyLL():
    def __init__(self,value):
        self.head=SinglyLLNode(value)

    def getTail(self):
        n=self.head
        while n.next != None:
            n = n.next
        return n

    def display(self):

        n = self.head
        a=[]
        while n != None:
            a.append(n.value)
            n = n.next

        print(*a,sep=" -> ")

    def insertT(self,value):
        n = self.getTail()
        n.next=SinglyLLNode(value)

    def deleteT(self):
        n=self.head

        if n is None:
            print("Cant Delete Empty List")
            return

        elif n.next is None:
            del n
            return
        else:
            prev = n
            while n.next is not None:
                prev = n
                n = n.next

            prev.next = n



N = SinglyLL(100)
N.insertT(123)
N.insertT(1234)
N.display()
N.deleteT()
N.insertT(12345)
N.display()

输出为:

100-> 123-> 1234

100-> 123-> 1234-> 12345

但应该是 100-> 123-> 12345

PS:对不起,对大代码来说,请看其他人运行良好的deleteT()函数

1 个答案:

答案 0 :(得分:1)

deleteT函数将删除链表的最后一个元素,确保新的最后一个元素指向None

def deleteT(self):
        n=self.head

        if n is None:
            print("Cant Delete Empty List")
            return

        elif n.next is None:
            del n
            return
        else:
            while n.next.next is not None:
                n = n.next
            del n.next.next
            n.next = None