题目:
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
这题很简单,直接上代码。
时间复杂度:O(n)
/**
* 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 || !head->next) return head;
ListNode *first=head,*second=head;
while(second->next)
{
if(second->val==second->next->val)
{
second=second->next;
continue;
}
first->next=second->next;
first=first->next;
second=first;
}
first->next=second->next;
return head;
}
};