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;
}
};