Python链表删除重复项

标签 python

我正在尝试编写代码来从排序的链接列表“head”中删除重复项。如果列表以重复项结尾,我下面的代码始终返回最后一个重复项。例如[1,2,2,3,3] 将返回 [1,2,3,3]。我不明白为什么。有人有想法吗?

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """

        if not head:
            return head

        l1=newhead=ListNode(head.val)
        head=head.next


        while head:
            if head.val!=l1.val:
                l1.next=head
                l1=l1.next
            head=head.next

        return newhead

最佳答案

您应该跟踪每个新值的前导节点并继续获取下一个节点,直到获得具有不同值的节点,此时您将该节点分配为前导节点的下一个节点:

class Solution(object):
    def deleteDuplicates(self, head):
        node = head
        while node:
            lead = node
            while node.next and node.next.val == lead.val:
                node = node.next
            node = lead.next = node.next
        return head

关于Python链表删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54043644/

相关文章:

Python - 加快将分类变量转换为其数字索引

python 3.5.2 "takes from 2 to 3 positional arguments but 4 were given"

python - 如何在Python中压缩两个数组并保持原始形状?

python - 记录来自 python-requests 模块的所有请求

python - 如何从不同位置的文本文件返回数字列表

python - 通过 Python 打印日历。代码不起作用=/

python - 转换新数据集以在 Python 中进行预测

python - 随着时间的推移改变变量

python - Heroku : request. 表单上的 Flask 在处理大量 POST 数据时速度非常慢?

python - 在 x 秒后运行某些代码,在 python 中每 n 秒运行一次