remove duplicates numbers (移除單鏈表中相同的元素)

問題
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.

要求刪除鏈表中相同的元素,最終只返回鏈表中不相同的元素。
問題分析
當我看到這個題目的時候,首先第一反應是跟之前的刪除鏈表中的相同的元素1->1->2->3->3, return 1->2->3.一樣,然後就想把那些重複的元素和之前的一樣一個一個刪除。
然後發現問題不是自己想象的那樣簡單,後來跟同學一討論,發現可以換一個思路,就是先找到第一次出現重複的數,統計這些重複的數的個數,然後將這些重複的數刪掉,然後再去考慮後面是否還有重複的數。
如: 1->2->3->3->4->4->5
首先找到3是重複的數,然後統計重複的3的個數爲2,刪掉。
再繼續看是否還有重複的數,找到4,統計重複的4的個數,刪掉
沒有重複的數,end

 
/**
* 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){
ListNode *pre = new ListNode(0); //save the pre node of head, used to head.val==head->next.val
ListNode *preHead = pre; //save the list
pre->next = head;
ListNode *curSame = head; //curSame used to visit the list.
while(head!=NULL){
int counter = 0; //save the number of duplicates
while(curSame!=NULL&&curSame->val==head->val){ //count the number of duplicates number in the list
curSame=curSame->next;
counter++;
}
if(counter>1){ //delete the duplicates number
pre->next=curSame;
head = curSame;
}
else if(counter==1){
//consider the situation: head.val!=head->next.val
pre = head;
head = curSame;
}
}
return preHead->next;
}
else{
return head;
}
}
};

發佈了22 篇原創文章 · 獲贊 5 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章