Skip to content

Latest commit

 

History

History
40 lines (35 loc) · 1.26 KB

82.md

File metadata and controls

40 lines (35 loc) · 1.26 KB

82. Remove Duplicates from Sorted List II

把一个有序链表中所有重复的数字全部删光,删除后不再有原先重复的那些数字

思路:用一个新的链表,将不重复的元素全部一一加上去

class Solution:
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        # 6 star, 需多练习
        # 思路类似双指针
        if not head:
            return None
        dummy = ListNode(-0xffffffff)
        dummy.next = head
        node = head
        _node = dummy # _node变量用来记录想要的目标链表的最后一个节点,从dummy节点开始,对后边的节点,如果节点重复则略过,不重复则往链表上接
        while node:
            if node.next:
                if node.val != node.next.val:
                    _node.next = node
                    node = node.next
                    _node = _node.next
                else:
                    val = node.val
                    while node and node.val == val:
                        node = node.next
            else:
                _node.next = node
                node = node.next
                _node = _node.next
        _node.next = None
        return dummy.next