problem:
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.
thinking:
(1)这道题是上一题的简化版,上一题是把重复的元素一个不留的删除:http://blog.csdn.net/hustyangju/article/details/45028247
(2)双指针遍历,时间复杂度O(N),一次提交AC
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 || head->next==NULL)
return head;
ListNode *p=head;//左指针
ListNode *q=p; //右指针
while(p!=NULL)
{
q=p->next; //右指针初始化
if(q==NULL)
return head;
if(p->val!=q->val) //不相等,同时前进
{
p=p->next;
q=q->next;
}
else //相等 ,右指针前进
{
while(q!=NULL && q->val==p->val)
{
q=q->next;
}
p->next=q; //删除重复元素
p=q; //更新左指针
}
}
return head;
}
};leetcode || 83、Remove Duplicates from Sorted List
原文地址:http://blog.csdn.net/hustyangju/article/details/45028639