1097 Deduplication on a Linked List (25 point(s))

本文探讨了使用C++实现链表中元素去重的两种方法,并详细对比了两段代码的优劣。作者首先展示了一段存在段错误的代码,然后提供了一个修正后的解决方案,重点在于如何正确地处理链表遍历和重复元素的记录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

求解

写了两种代码,不过第一种还是不知道错在哪,有知道的老铁麻烦告知一下,谢谢。

#include<iostream>
#include<cstdio>
#include<vector>
#include<cmath>
using namespace std;
const int MAXN = 1e6;
const int MAXM = 1e4 + 10;
struct node {
	int key, addrnext;
}t[MAXN];
vector<int> res, dup;
int book[MAXN];
int main() {
	int first, n, x;
	scanf("%d%d", &first, &n);
	for(int i = 0; i < n; ++i) {
		scanf("%d", &x);
		scanf("%d%d", &t[x].key, &t[x].addrnext);
	}
	while(first != -1) {
		if(book[abs(t[first].key)] == 0) {
			book[abs(t[first].key)] = 1;
			res.push_back(first);
		} else dup.push_back(first);
		first = t[first].addrnext;
	}
	for(int i = 0; i < res.size() - 1; ++i) printf("%05d %d %05d\n", res[i], t[res[i]].key, res[i + 1]);
	if(res.size())	printf("%05d %d -1\n", res[res.size() - 1], t[res[res.size() - 1]].key); 
	for(int i = 0; i < dup.size() - 1; ++i) printf("%05d %d %05d\n", dup[i], t[dup[i]].key, dup[i + 1]);
	if(dup.size())	printf("%05d %d -1", dup[dup.size() - 1], t[dup[dup.size() - 1]].key);
	return 0;
}



/*这一种可以求解上一种为什么会段错误

	if(res.size()){
		for(int i = 0; i < res.size() - 1; ++i) printf("%05d %d %05d\n", res[i], t[res[i]].key, res[i + 1]);
		printf("%05d %d -1\n", res[res.size() - 1], t[res[res.size() - 1]].key); 
	}
	if(dup.size()) {
		for(int i = 0; i < dup.size() - 1; ++i) printf("%05d %d %05d\n", dup[i], t[dup[i]].key, dup[i + 1]);
		printf("%05d %d -1\n", dup[dup.size() - 1], t[dup[dup.size() - 1]].key);
	}
*/

AC的代码。。。

#include<iostream>
#include<cstdio>
#include<vector>
#include<cmath>
using namespace std;
const int MAXN = 1e6;
const int MAXM = 1e4 + 10;
struct node {
	int key, addrnext;
}t[MAXN];
vector<int> res, dup;
int book[MAXM];
int main() {
	int first, n, x;
	scanf("%d%d", &first, &n);
	for(int i = 0; i < n; ++i) {
		scanf("%d", &x);
		scanf("%d%d", &t[x].key, &t[x].addrnext);
	}
	while(first != -1) {
		if(book[abs(t[first].key)] == 0) {
			book[abs(t[first].key)] = 1;
			res.push_back(first);
		} else dup.push_back(first);
		first = t[first].addrnext;
	}
	for(int i = 0; i < res.size(); ++i) 
		if(i == res.size() - 1) printf("%05d %d -1\n", res[i], t[res[i]].key);
		else printf("%05d %d %05d\n", res[i], t[res[i]].key, res[i + 1]);
	for(int i = 0; i < dup.size(); ++i) 
		if(i == dup.size() - 1) printf("%05d %d -1\n", dup[i], t[dup[i]].key);
		else printf("%05d %d %05d\n", dup[i], t[dup[i]].key, dup[i + 1]);
	return 0;
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值