leetcode 【 Remove Duplicates from Sorted List II 】 python 实现
2014-12-26 15:20
507 查看
题目:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given
Given
代码:oj在线测试通过 288 ms
思路:
设立虚表头 hummyhead 这样处理Linked List方便一些
p.next始终指向待比较的元素
while循环中再嵌套一个while循环,把重复元素都跳过去。
如果遇到了重复元素:p不动,p.next变化;如果没有遇到重复元素,则p=p.next
Tips: 使用指针之前 最好加一个逻辑判断 指针不为空
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
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return a ListNode def deleteDuplicates(self, head): if head is None or head.next is None: return head dummyhead = ListNode(0) dummyhead.next = head p = dummyhead while p.next is not None and p.next.next is not None: tmp = p while tmp.next.val == tmp.next.next.val: tmp = tmp.next if tmp.next.next is None: break if tmp == p: p = p.next else: if tmp.next.next is not None: p.next = tmp.next.next else: p.next = tmp.next.next break return dummyhead.next
思路:
设立虚表头 hummyhead 这样处理Linked List方便一些
p.next始终指向待比较的元素
while循环中再嵌套一个while循环,把重复元素都跳过去。
如果遇到了重复元素:p不动,p.next变化;如果没有遇到重复元素,则p=p.next
Tips: 使用指针之前 最好加一个逻辑判断 指针不为空
相关文章推荐
- 【Leetcode】【python】Remove Duplicates from Sorted List/Remove Duplicates from Sorted List II
- [leetcode]Remove Duplicates from Sorted List II @ Python
- C实现 LeetCode->Remove Duplicates from Sorted List II(枚举法)(单链表)
- 【LeetCode-面试算法经典-Java实现】【082-Remove Duplicates from Sorted List II(排序链表中删除重复元素II)】
- leetcode 【 Remove Duplicates from Sorted List 】 python 实现
- [LeetCode]题解(python):082-Remove Duplicates from Sorted List II
- 【LEETCODE】82- Remove Duplicates from Sorted List II [Python]
- [LeetCode]Remove Duplicates from Sorted List II@python
- 【LeetCode with Python】 Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- LeetCode-Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List、Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- leetcode Remove Duplicates from Sorted List I && II
- LeetCode | Remove Duplicates from Sorted List II
- LeetCode-Remove Duplicates from Sorted List II
- [面试真题] LeetCode:Remove Duplicates from Sorted List I & II
- [LeetCode]Remove Duplicates from Sorted List II
- leetcode 38: Remove Duplicates from Sorted List II
- leetcode -- Remove Duplicates from Sorted List II