Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
从前向后遍历,使用三个指针进行操作,画图理解
代码:
/**
* 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;
if (head->next==NULL) return head;
ListNode* first,*second;
ListNode* prehead=new ListNode(0);
prehead->next=head;
first=head;
second=first->next;
int flag=0;
ListNode* prefirst=prehead;
while(second)
{
if (first->val==second->val)
{
flag=1;
prefirst->next=second;
first=second;
second=second->next;
}
else
{
if (flag)
{
prefirst->next=second;
first=second;
second=second->next;
}
else
{
prefirst=first;
first=second;
second=second->next;
}
flag=0;
}
}
if (flag)
{
prefirst->next=NULL;
}
return prehead->next;
}
};