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.
题意是:给一个链表,找出链表中重复的节点,将这些节点去掉。
思路是分两块处理,第一块处理当头节点是重复的,直接前面跟头节点相同的去掉,然后再继续遍历(这里应该是不用这样的,后面再改吧), 然后同样的使用两个指针p,q去寻找遍历链表,q指向p的下一个节点, 如果具有相同节点的数超过2,则不断地将q->next指向q->next->next, 最后再将p->next来指向q->next->next(新的值),
具体代码如下:
ListNode* deleteDuplicates(ListNode* head)
{
if(head==nullptr||head->next==nullptr)//一个节点或空链表
{
return head;
}
ListNode *re=nullptr;
//先处理头节点
while(head->next!=nullptr&&head->val==head->next->val)//重复的
{
while(head->next!=nullptr&&head->next->val==head->val)
{
head=head->next;
}
head=head->next;
if(head==nullptr)
{
break;
}
}
if(head==nullptr)
{
return re;
}
//return head;
ListNode *p=head;
ListNode *q=head->next;
ListNode *helper;
//处理后面的节点
while(q!=nullptr)//&&q->next!=nullptr)
{
if(q->val==q->next->val)
{
while(q->next->next!=nullptr&&q->next->val==q->next->next->val)
{
helper=q->next->next;
q->next->next=nullptr;
q->next=helper;
}
helper=q->next->next;
q->next->next=nullptr;
p->next=helper;
q=p->next;
if(q==nullptr)
{
break;
}
}
else{
p=p->next;
q=q->next;
}
}
return head;
}