简体   繁体   English

LinkedList python 删除问题 function

[英]LinkedList python trouble with delete function

I'm writing a simple linked list code in Python, could you tell me whats wrong with the deleteT function.我在Python中写了一个简单的链表代码,你能告诉我deleteT function有什么问题吗? it's not doing its job它没有做它的工作

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()

the output is: output 是:

100 -> 123 -> 1234 100 -> 123 -> 1234

100 -> 123 -> 1234 -> 12345 100 -> 123 -> 1234 -> 12345

but should be 100 -> 123 -> 12345但应该是 100 -> 123 -> 12345

PS: Sorry for big code kindly just see the deleteT() function others are working well PS:对不起大代码请看deleteT() function 其他人工作良好

This deleteT function will remove the last element of the linked list, ensuring the the new last element points to None :这个deleteT function 将删除链表的最后一个元素,确保新的最后一个元素指向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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM