![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e7b8e46d9b27dea28604b5650cf2334c.jpeg)
- /方法一:借助set容器遍历链表筛选,再重新建立链表/
#include<iostream>
#include <vector>
#include <set>
using namespace std;
struct Node {
Node* next;
int data;
Node(int x) :data(x), next(NULL) {}
};
void PrintList(Node* head)
{
Node* phead = head;
while (phead != nullptr)
{
if (phead->next == nullptr)
cout << phead->data << endl;
else
cout << phead->data<<"->";
phead = phead->next;
}
}
void PrintSet(set<int>& st)
{
for (auto it : st)
{
cout << it<<" ";
}
cout << endl;
}
void PrintArr(vector<int>& vec)
{
for (auto aa : vec)
{
cout << aa << " ";
}
cout << endl;
}
set<int> ArrToSet(vector<int>& vec)
{
set<int>st;
for (int i = 0; i < vec.size(); i++)
{
st.insert(vec[i]);
}
return st;
}
Node* SetToList(set<int>& st)
{
Node* head=new Node(-1);
Node* phead = head;
set<int>::iterator it;
for (it = st.begin(); it != st.end(); it++)
{
Node* NewNode = new Node(*it);
phead->next = NewNode;
phead = phead->next;
}
return head->next;
}
Node* ArrToList(vector<int>& vec)
{
Node* head=new Node(vec[0]);
Node* phead = head;
for (int i = 1; i < vec.size(); i++)
{
Node* NewNode = new Node(vec[i]);
phead->next = NewNode;
phead = phead->next;
}
return head;
}
vector<int> ListToArr(Node* head)
{
vector<int> res;
Node* phead = head;
while (phead != nullptr)
{
res.push_back(phead->data);
phead = phead->next;
}
return res;
}
set<int> Del_Dup_Value(vector<int> &vec)
{
set<int> st;
for (auto ii : vec)
{
st.insert(ii);
}
return st;
}
int main()
{
vector<int> vec = {1,1,2,3,3};
PrintArr(vec);
Node* head1 = ArrToList(vec);
PrintList(head1);
set<int> st = Del_Dup_Value(vec);
PrintSet(st);
Node* head2 = SetToList(st);
PrintList(head2);
return 0;
}
- /方法二:原链表进行更改(遍历相等指向下一个元素继续比,不相等直接不改变)/
#include<iostream>
#include <vector>
#include <set>
using namespace std;
struct Node {
Node* next;
int data;
Node(int x) :data(x), next(NULL) {}
};
void PrintList(Node* head)
{
Node* phead = head;
while (phead != nullptr)
{
if (phead->next == nullptr)
cout << phead->data << endl;
else
cout << phead->data << "->";
phead = phead->next;
}
}
void PrintArr(vector<int>& vec)
{
for (auto aa : vec)
{
cout << aa << " ";
}
cout << endl;
}
Node* ArrToList(vector<int>& vec)
{
Node* head = new Node(vec[0]);
Node* phead = head;
for (int i = 1; i < vec.size(); i++)
{
Node* NewNode = new Node(vec[i]);
phead->next = NewNode;
phead = phead->next;
}
return head;
}
vector<int> ListToArr(Node* head)
{
vector<int> res;
Node* phead = head;
while (phead != nullptr)
{
res.push_back(phead->data);
phead = phead->next;
}
return res;
}
Node* Del_Dup_Value(Node* head)
{
Node* phead = head;
while ( phead->next != nullptr) {
if (phead->data == phead->next->data) {
phead->next = phead->next->next;
}
else {
phead = phead->next;
}
}
return head;
}
int main()
{
vector<int> vec = { 1,1,1,2,2,3,3,3};
PrintArr(vec);
Node* head1 = ArrToList(vec);
PrintList(head1);
Node* head2 = Del_Dup_Value(head1);
PrintList(head2);
return 0;
}