82. Remove Duplicates from Sorted List II(Python3)

82. Remove Duplicates from Sorted List II(Python3)

题目

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

解题方案

思路:

  • 该题并不复杂,主要是指针的操作,其中要注意的是,最后一个元素如果有多个相同的要进行剔除,这里的处理

代码:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return head
        tmp = ListNode(0)
        tmp.next = head
        pre = tmp
        front = head
        end = head.next
        flag = False
        while end:
            if front.val == end.val:
                end = end.next
                flag = True
            elif flag:
                pre.next,front,end = end,end,end.next
                flag = False
            else:
                pre,front,end = front,end,end.next
        if flag:
            pre.next = None
        return tmp.next

你可能感兴趣的:(leetcode)