这次一共写了四个版本,可谓一波三折,试了很多方法。
版本一:利用指针,成功
版本二:将链表中节点的值存储到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;
}
};
*/