這次一共寫了四個版本,可謂一波三折,試了很多方法。
版本一:利用指針,成功
版本二:將鏈表中節點的值存儲到vector裏面,然後去除重複元素,再將剩下的元素生成新的鏈表,利用vector的unique方法,但是沒成功
原因分析:
我們在代碼一開始生成了vector temp = [1,2,3,3,4,4,5],一開始錯誤以爲unique方法能將重複元素2,2,3,3都放置在最後面變爲[1,2,5,3,3,4,4],然而實際上爲[1,2,3,4,5,3,4],導致失敗,所以後面採取了暴力法,一個一個直接比較。
版本三:同版本二,過程不一樣,暴力法,成功
版本四:利用map,沒成功。準備利用map,生成{1:1, 2:1, 3:2, 4:2, 5:1},然後根據鍵值value是否爲1進行選擇,將key值生成新的鏈表。這個示例沒問題,因爲它是有序排列,但是當提交的時候示例爲[2,1]的時候,期望生成的map應該爲{2:1, 1:1},即按照輸入順序排列,但是實際上map內部是按照key的大小關係進行有機排序,所以實際map爲{1:1, 2:1},導致生成的鏈表順序不一致。
總結:對vector的unique函數不熟悉,不熟悉map裏面的排序機制,對應的還有unordered_map內部排序機制和map也不一樣。此處應該多看資料。
/**
* 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) {
ListNode *prehead = new ListNode(0);
prehead->next = head;
ListNode *cur = prehead;
int delVal = -10;//沒有初始值會報錯
while(cur->next){
if(cur->next->next && cur->next->val == cur->next->next->val){
ListNode *delPtr = cur->next->next;
delVal = cur->next->val;
if(delPtr->next)
cur->next = delPtr->next;
else
cur->next = nullptr;
delete delPtr;
}
else{
if(cur->next->val == delVal)
cur->next = cur->next->next;
else
cur = cur->next;
}
}
return prehead->next;
}
};
//版本二,先把值全部放在數組裏,去掉相同值 no ok
class Solution{
public:
ListNode *deleteDuplicates(ListNode *head){
ListNode *p = head;
if(!p)
return nullptr;
vector<int> temp{};
while(p){
temp.push_back(p->val);
if(p->next)
p = p->next;
else
p = nullptr;
}
delete p;
auto new_end = unique(temp.begin(),temp.end());
temp.erase(new_end,temp.end());
ListNode *Ret = new ListNode(temp[0]);
ListNode *ret = Ret;
for(auto it=temp.begin()+1; it!=temp.end(); it++){
cout<<*it<<endl;
ret->next = new ListNode(*it);
ret = ret->next;
}
return Ret;
}
};
// 版本三 ok
class Solution{
public:
ListNode *deleteDuplicates(ListNode *head){
ListNode *p = head;
if(!p)
return nullptr;
vector<int> temp{-10};
while(p){
temp.push_back(p->val);
if(p->next)
p = p->next;
else
p = nullptr;
}
delete p;
ListNode *Ret = new ListNode(-10);
ListNode *ret = Ret;
for(int i=1; i<temp.size(); i++){
if(i+1<temp.size() && temp[i] != temp[i+1] && temp[i] != temp[i-1]){
cout<<temp[i]<<endl;
ret->next = new ListNode(temp[i]);
ret = ret->next;
}
else if(i==temp.size()-1 && temp[temp.size()-1]!=temp[temp.size()-2]){
ret->next = new ListNode(temp[temp.size()-1]);
ret= ret->next;
}
else
continue;
}
return Ret->next;
}
};
//版本四,map no ok
class Solution{
public:
ListNode *deleteDuplicates(ListNode *head){
ListNode *p = head;
if(!p)
return nullptr;
map<int, int> temp;
while(p){
//temp.insert(pair<int,int>(p->val,++temp[p->val]));
temp[p->val]++;
if(p->next)
p = p->next;
else
p = nullptr;
}
delete p;
ListNode *Ret = new ListNode(-10);
ListNode *ret = Ret;
for(const auto &c:temp){
if(c.second==1){
ret->next = new ListNode(c.first);
ret = ret->next;
}
}
return Ret->next;
}
};
*/