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 || !head->next) return head;
ListNode dummy(-1);
dummy.next = head;
ListNode *pre = &dummy;
ListNode *cur = head;
ListNode *post = head->next;
bool flag = false;
while (cur && post)
{
while (post && cur->val == post->val)
{
post = post->next;
flag = true;
}
if (flag == true) pre->next = post;
else pre = pre->next;
flag = false;
cur = post;
if (post) post = post->next;
}
//不能用return head, 因为如果head重复的话,需要删掉head,但是其实head还在内存中,没有删掉,不过改变了dummy->next的链表。
return dummy.next;
}
};
//2014-2-13 update
ListNode *deleteDuplicates(ListNode *head)
{
if (!head || !head->next) return head;
ListNode dummy(0);
ListNode *p = &dummy;
bool repeat = false;
for ( ;head->next; head = head->next)//记得步进head
{
if (head->val == head->next->val) repeat = true;
else
{
if (repeat) repeat = false;
else//不重复的才加入新的链表中
{
p->next = head;
p = p->next;
}
}
}
if (!repeat)//注意别漏掉
{
p->next = head;
p = p->next;
}
p->next = nullptr; //注意:删除结尾多余的节点。
return dummy.next;
}