【LeetCode每天一题】 Remove Duplicates from Sorted List II(移除有序链表中重复的节点)

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

Example 1:

  Input: 1->2->3->3->4->4->5
  Output: 1->2->5

Example 2:

  Input: 1->1->1->2->3
  Output: 2->3

思路

  这道题和上一道题目有一点区别的就是移除所有相同的节点,只留下没有重复的节点。对于这这个题目我们可以使用一个指针指向未重复的节点,然后另外一个指针来跳过重复的节点,一直到最后为止。这里我们使用了哨兵机制来记录结果的头节点。时间复杂度为O(n), 空间复杂度为O(1)。
解决图示

 
解决代码

 
 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def deleteDuplicates(self, head):
 9         if not head or not head.next:  # 为空和只有一个节点直接返回
10             return head        
11         res, cur = ListNode(0), head    # 设置哨兵节点
12         pre = res                   
13         while pre and cur:                # 循环结束条件
14             while cur.next and cur.val == cur.next.val:   # 判断该节点和下一个节点是否相等
15                 tem1= cur.val
16                 while cur and cur.val == tem1:           # 一直遍历到下一个和该节点不相等为止。
17                     cur = cur.next
18                 if not cur:             # 是否到为尾节点了
19                     pre.next = cur
20                     return res.next      # 直接返回
21             pre.next = cur             # 说明当前节点与下一个节点不相等,移动pre和cur指针为止
22             pre = pre.next
23             cur = cur.next
24         return res.next                 # 返回节点位置

猜你喜欢

转载自www.cnblogs.com/GoodRnne/p/10799557.html