PAT A1097 Deduplication on a Linked List (25分)

在这里插入图片描述

#include <cstdio>
#include <map>
#include <cstdlib>

using namespace std;

struct Node{
	int address, data, next;
	int flag;
}node[100010];

map<int,int> m;

int main(){
	int h, n;
	scanf("%d %d", &h, &n);
	
	int ad;
	for(int i=0; i<n; i++){
		scanf("%d", &ad);
		node[ad].address = ad;
		scanf("%d %d", &node[ad].data, &node[ad].next); 
	}
	
	Node temp[100010];
	int num = 0;
	while(h != -1){
		m[abs(node[h].data)]++;
		int next = node[h].next;
		while(next!=-1 && m[abs(node[next].data)]>0){
			temp[num++] = node[next];
			node[h].next = node[next].next;
			next = node[next].next;
		}
		if(next != -1){
			printf("%05d %d %05d\n", h, node[h].data, next);	
		}else{
			printf("%05d %d -1\n", h, node[h].data);
		}
		h = next;
	}
	
	for(int i=0; i<num-1; i++){
		printf("%05d %d %05d\n", temp[i].address, temp[i].data, temp[i+1].address);	
	}
	if(num != 0){
		printf("%05d %d -1\n", temp[num-1].address, temp[num-1].data);
	}
	
	return 0;
}

哎呀差点一次AC了,被测试点2卡了一下,这个测试点应该是重复链表为空时不需要输出任何东西。
这题的做法是遍历链表的同时用map记录下每个key值是否出现过,如果当前结点的下一个结点的值已经出现过了,则当前结点的next为下一个结点的next,同时再建一个temp数组来保存被跳过的结点以便最后输出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值