给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
c++解题
/**
* 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*i=head;//慢指针
ListNode*j=head->next;//快指针
while(i->next!=NULL)
{
if(i->val==j->val)//寻找重复元素
{
if(j->next==NULL)//快指针后无元素
{
i->next=NULL;//删去
}
else
{
i->next=j->next;
j=j->next;
}
}
else//元素不重复
{
i=i->next;
j=j->next;
}
}
return head;
}
};