L2-002 链表去重 (25 point(s))
给定一个带整数键值的链表 L,你需要把其中绝对值重复的键值结点删掉。即对每个键值 K,只有第一个绝对值等于 K 的结点被保留。同时,所有被删除的结点须被保存在另一个链表上。例如给定 L 为 21→-15→-15→-7→15,你需要输出去重后的链表 21→-15→-7,还有被删除的链表 -15→15。
输入格式:
输入在第一行给出 L 的第一个结点的地址和一个正整数 N( N ≤ 1 0 5 N≤10^5 N≤105 ,为结点总数)。一个结点的地址是非负的 5 位整数,空地址 NULL 用 −1 来表示。
随后 N 行,每行按以下格式描述一个结点:
地址 键值 下一个结点
其中地址是该结点的地址,键值是绝对值不超过
1
0
4
10 ^4
104 的整数,下一个结点是下个结点的地址。
输出格式:
首先输出去重后的链表,然后输出被删除的链表。每个结点占一行,按输入的格式输出。
输入样例:
00100 5
99999 -7 87654
23854 -15 00000
87654 15 -1
00000 -15 99999
00100 21 23854
输出样例:
00100 21 23854
23854 -15 99999
99999 -7 -1
00000 -15 87654
87654 15 -1
思路:
这道题一看输入输出就知道是静态链表的问题
我们要做的就是根据输入建立静态链表
定义放重复节点的链表
遍历静态链表把重复的节点从链表上取下来连接到放重复节点的链表
最后输出两个链表就可以了
AC代码
#include <bits/stdc++.h>
using namespace std;
const int SIZE = 1e5 + 1;
const int null = -1;// 结束的标记
typedef int NodeType;
struct SNode {
NodeType val; // 节点值
int next; // 指向下一个节点的指针
} sl[SIZE]; // 这就是静态链表了
int dupl[SIZE]; // 用来检测是否重复
int main(int argc, char const* argv[]) {
// ifstream cin("D:\\workspaceFolder\\CODE_CPP\\a.txt");
memset(dupl, 0, sizeof dupl);
int head, n, addr;
cin >> head >> n;
while (n--)
cin >> addr >> sl[addr].val >> sl[addr].next;
int head2 = null, pre2 = 0, pre = head;
for (int i = head; i != null; i = sl[i].next) { // 去重
if (!dupl[abs(sl[i].val)]) {
dupl[abs(sl[i].val)] = 1;
pre = i;
} else {
sl[pre].next = sl[i].next; // 从sl1上解下来
if (head2 == null) // 连到sl2上
head2 = i;
else
sl[pre2].next = i;
pre2 = i;
}
}
sl[pre2].next = null; // 结尾
for (int i = head; i != null; i = sl[i].next) { // 输出
if (sl[i].next != null)
printf("%05d %d %05d\n", i, sl[i], sl[i].next);
else
printf("%05d %d %d\n", i, sl[i], sl[i].next);
}
for (int i = head2; i != null; i = sl[i].next)
if (sl[i].next != null)
printf("%05d %d %05d\n", i, sl[i], sl[i].next);
else
printf("%05d %d %d\n", i, sl[i], sl[i].next);
return 0;
}
最后,有一个小小的坑就是输出的格式