删除重复元素-链表
题目
https://kamacoder.com/problem.php?id=1019
题解
#include<iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct LinkNode {
int data;
LinkNode *next;
LinkNode(int data) : data(data), next(nullptr) {}
};
LinkNode* deleteDuplicateList(LinkNode *cur)
{
LinkNode *curNext = cur->next;
while (cur && curNext)
{
if (cur->data == curNext->data) // 相等就不需要移动cur,下次循环判断
{
LinkNode *tmp = curNext->next;
delete curNext;
curNext = nullptr;
cur->next = tmp;
curNext = cur->next;
}
else
{
cur = cur->next;
curNext = curNext->next;
}
}
return cur;
}
void printList(LinkNode *cur)
{
while (cur)
{
cout << cur->data << ' ';
cur = cur->next;
}
cout << endl;
}
int main()
{
int n, tmp;
LinkNode *dummyNode = new LinkNode(0);
while (cin >> n)
{
vector<int> vec;
if (n == 0)
{
cout << "list is empty" << endl;
continue;
}
LinkNode *cur = dummyNode;
for (int i = 0; i < n; ++i)
{
cin >> tmp;
vec.push_back(tmp);
}
sort(vec.begin(), vec.end());
for (auto v : vec)
{
LinkNode *node = new LinkNode(v);
cur->next = node;
cur = node;
}
printList(dummyNode->next);
deleteDuplicateList(dummyNode->next);
printList(dummyNode->next);
}
return 0;
}