团体天梯 L2-002 链表去重 (25 分)

版权声明:就是码字也不容易啊 https://blog.csdn.net/qq_40946921/article/details/86516978

L2-002 链表去重 (25 分)

给定一个带整数键值的链表 L,你需要把其中绝对值重复的键值结点删掉。即对每个键值 K,只有第一个绝对值等于 K 的结点被保留。同时,所有被删除的结点须被保存在另一个链表上。例如给定 L 为 21→-15→-15→-7→15,你需要输出去重后的链表 21→-15→-7,还有被删除的链表 -15→15。

输入格式:

输入在第一行给出 L 的第一个结点的地址和一个正整数 N(≤10​5​​,为结点总数)。一个结点的地址是非负的 5 位整数,空地址 NULL 用 −1 来表示。

随后 N 行,每行按以下格式描述一个结点:

地址 键值 下一个结点

其中地址是该结点的地址,键值是绝对值不超过10​4​​的整数,下一个结点是下个结点的地址。

输出格式:

首先输出去重后的链表,然后输出被删除的链表。每个结点占一行,按输入的格式输出。

输入样例:

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
#include<iostream>
#include<map>
#include<vector>
using namespace std;
struct Node {
	int ads,data, next;
};
int main() {
	int n, str, start,  key[10001] = {0};
	map<int, Node> m;
	vector<Node> out[2];
	cin >> start >> n ;
	for (int i = 0; i < n; i++) {
		scanf("%d", &str);         //输入结点数据
		scanf("%d %d", &m[str].data, &m[str].next);
	}
	for (int i = 0; i < n; i++) {  //通过map直接索引start将链表按顺序转到node数组里面
		if (key[abs(m[start].data)] == 0) {
			out[0].push_back({ start,m[start].data ,0 });
			key[abs(m[start].data)] = 1;
		}
		else
			out[1].push_back({ start,m[start].data ,0 });
		start = m[start].next;
		if (start == -1)     //当start被赋值为-1的时候,链表就结束了,更新n的值,测试点1
			n = i + 1;
	}
	for (int i = 0; i < 2; i++) {
		for (int j = 0; j < out[i].size(); j++) {   //输出
			printf("%05d %d ", out[i][j].ads, out[i][j].data);
			if (j != out[i].size() - 1)
				printf("%05d\n", out[i][j + 1].ads);
			else
				printf("-1\n");  //最后一个结点next为-1
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40946921/article/details/86516978