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 <vector>
#include <map>
using namespace std;
struct Node {
	int address,
		data,
		next;
};
int main() {
	map<int, Node>link;
	vector<Node>ans[2];
	int head, N, tmp, vis[10001] = { 0 };
	cin >> head >> N;
	for (int i = 0; i < N; ++i) {
		cin >> tmp;
		cin >> link[tmp].data >> link[tmp].next;
	}
	while (head != -1) {
		if (vis[abs(link[head].data)]++ == 0)
			ans[0].push_back({ head, link[head].data,0 });
		else
			ans[1].push_back({ head, link[head].data,0 });
		head = link[head].next;
	}
	for (int i = 0; i < 2; ++i)
		for (int j = 0; j < ans[i].size(); ++j)
			j + 1 == ans[i].size() ? printf("%05d %d -1\n", ans[i][j].address, ans[i][j].data) : printf("%05d %d %05d\n", ans[i][j].address, ans[i][j].data, ans[i][j + 1].address);
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章