82. Remove Duplicates from Sorted List II
problem description
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers 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
algorithm thought
又是链表问题,并且直接返回一个链表。和之前做链表题一样直接用递归的形式解决
code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head==NULL)
return NULL;
ListNode* now=head;
head=head->next;
if(head&&head->val==now->val){
while(head&&head->val==now->val)
head=head->next;
return deleteDuplicates(head);
}else{
now->next=deleteDuplicates(head);
return now;
}
}
};
algorithm analysis
一次遍历解决,时间复杂度O(n)
Last updated