[Lintcode]112. Remove Duplicates from Sorted List/[Lintcode]83. Remove Duplicates from Sorted List
112. Remove Duplicates from Sorted List/83. Remove Duplicates from Sorted List
- 本题难度: Easy/Medium
- Topic: Linked List
Description
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example
Example 1:
Input: null
Output: null
Example 2:
Input: 1->1->2->null
Output: 1->2->null
Example 3:
Input: 1->1->2->->3->3->null
Output: 1->2->3->null
Example
Example 1:
Input: null
Output: null
Example 2:
Input: 1->1->2->null
Output: 1->2->null
Example 3:
Input: 1->1->2->->3->3->null
Output: 1->2->3->null
我的代码
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: head is the head of the linked list
@return: head of linked list
"""
def deleteDuplicates(self, head):
# write your code here
if head is None:
return head
pos = head
while(pos.next):
if (pos.next).val == pos.val:
pos.next = (pos.next).next
else:
pos = pos.next
return head
思路
排序队列,所以只需要存前一个的value就好了。
特殊情况:
- 空
- 只有一个元素时(不需要单独讨论)
- 时间复杂度 O(n)
- 出错
当删去重复的数字后不要往前走,因为可能存在前面还是重复的情况