首页 > 代码库 > leetcode 【 Remove Duplicates from Sorted List II 】 python 实现

leetcode 【 Remove Duplicates from Sorted List II 】 python 实现

题目

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.

 

代码:oj在线测试通过 288 ms

 1 # Definition for singly-linked list. 2 # class ListNode: 3 #     def __init__(self, x): 4 #         self.val = x 5 #         self.next = None 6  7 class Solution: 8     # @param head, a ListNode 9     # @return a ListNode10     def deleteDuplicates(self, head):11         if head is None or head.next is None:12             return head13         14         dummyhead = ListNode(0)15         dummyhead.next = head16         17         p = dummyhead18         while p.next is not None and p.next.next is not None:19             tmp = p20             while tmp.next.val == tmp.next.next.val:21                 tmp = tmp.next22                 if tmp.next.next is None:23                     break24             if tmp == p:25                 p = p.next26             else:27                 if tmp.next.next is not None:28                     p.next = tmp.next.next29                 else:30                     p.next = tmp.next.next31                     break32         return dummyhead.next

 

思路

设立虚表头 hummyhead 这样处理Linked List方便一些

p.next始终指向待比较的元素

while循环中再嵌套一个while循环,把重复元素都跳过去。

如果遇到了重复元素:p不动,p.next变化;如果没有遇到重复元素,则p=p.next

Tips: 使用指针之前 最好加一个逻辑判断 指针不为空

leetcode 【 Remove Duplicates from Sorted List II 】 python 实现