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
.
思路:记录当前节点,当前节点的前一个节点,当前节点的后一个节点;
首先找到第一个不重复的头节点,前一个节点和当前节点若相等,则注意更新头节点。
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head == NULL)
return NULL;
if(head->next == NULL)
return head;
int flag = 1;
ListNode * pre;/*后一个 节点*/
ListNode * p;/* 当前节点*/
ListNode * last;/*重复节点的前一个*/
ListNode * q;/*删除的临时节点*/
/*得到第一个不重复的head*/
pre = head->next;
p = head;
while(p->val == pre->val && pre!=NULL)
{
flag = 0;
head = head->next;
p = p->next;
pre = pre->next;
if(head == NULL)
return NULL;
if(pre == NULL)
return NULL;
}
if(flag == 0)
head = head ->next;/*head 不重复*/
//printf("%d %d\n",head->val,head->next->val);
if(head->next == NULL)
return head;
if(head->val == head->next->val && head->next == NULL)
{
return NULL;
}
pre = head->next;
p = head;
last = p;
while(pre != NULL)
{
flag = 1;
while(pre != NULL && (pre->val == p->val))
{
flag = 0;
q = pre;
pre = pre->next;
p->next = pre;
delete(q);
}
if(flag == 0)
{
if(pre == NULL)
{
if(last == p)
return NULL;
last->next = NULL;
return head;
}
else
{
if(last == p)
{
head = head->next;
p = head;
last = p;
pre = pre->next;
continue;
}
q = p;
p = last;
p->next = pre;
delete(q);
p = p->next;
pre = pre->next;
}
flag = 1;
}
else
{
last = p;
p = p->next;
pre=pre->next;
}
}
return head;
}
};