其他分享
首页 > 其他分享> > PAT甲级1097

PAT甲级1097

作者:互联网

PAT甲级1097

原题:
1097 Deduplication on a Linked List (25 分)
Given a singly linked list L with integer keys, you are supposed to remove the nodes with duplicated absolute values of the keys. That is, for each value K, only the first node of which the value or absolute value of its key equals K will be kept. At the mean time, all the removed nodes must be kept in a separate list. For example, given L being 21→-15→-15→-7→15, you must output 21→-15→-7, and the removed list -15→15.

Input Specification:
Each input file contains one test case. For each case, the first line contains the address of the first node, and a positive N (≤10
​5
​​ ) which is the total number of nodes. The address of a node is a 5-digit nonnegative integer, and NULL is represented by −1.

Then N lines follow, each describes a node in the format:

Address Key Next
where Address is the position of the node, Key is an integer of which absolute value is no more than 10
​4
​​ , and Next is the position of the next node.

Output Specification:
For each case, output the resulting linked list first, then the removed list. Each node occupies a line, and is printed in the same format as in the input.

Sample Input:
00100 5
99999 -7 87654
23854 -15 00000
87654 15 -1
00000 -15 99999
00100 21 23854
Sample Output:
00100 21 23854
23854 -15 99999
99999 -7 -1
00000 -15 87654
87654 15 -1

题目大意:要求去掉绝对值相同的数据只保留第一个,去掉的数据也要输出

注意点:
1、题目是以链表的形式给出的,但是可以用多个数组进行模拟,把处理好的数据按顺序放在数组里,每次输出完该节点序号和data后直接输出下个节点的序号,不用特意串起来
2、不保证一定都是有用数据(未测试),我直接用的两个cnt分别记录收录了多少数据
3、开个flag数组记录每个data绝对值是否是第一次出现

#include <iostream>
using namespace std;

const int MAXN=100000;
int main(){
	int first,n;
	scanf("%d%d",&first,&n);
	int cnt1=0,cnt2=0;
	int data[MAXN],next[MAXN],ans1[MAXN],ans2[MAXN];	//ans1保存无重复的数据节点,ans2保存重复数据节点
	bool flag[10001]={false};	//flag记录每个data绝对值是否已经记录过
	for(int i=0;i<n;i++){
		int index;
		scanf("%d",&index);
		scanf("%d%d",&data[index],&next[index]);
	}
	while(first!=-1){
		if(flag[abs(data[first])]==false){	//若该数据绝对值未被收录过则接收到ans1中
			ans1[cnt1++]=first;
			flag[abs(data[first])]=true;
		}else{	//若绝对值已经收录过则存放到ans2中
			ans2[cnt2++]=first;
		}
		first=next[first];
	}
	for(int i=0;i<cnt1;i++)
		if(i!=cnt1-1)
			printf("%05d %d %05d\n",ans1[i],data[ans1[i]],ans1[i+1]);
		else
			printf("%05d %d -1\n",ans1[cnt1-1],data[ans1[cnt1-1]]);
	for(int i=0;i<cnt2;i++)
		if(i!=cnt2-1)
			printf("%05d %d %05d\n",ans2[i],data[ans2[i]],ans2[i+1]);
		else
			printf("%05d %d -1\n",ans2[cnt2-1],data[ans2[cnt2-1]]);
	system("pause");
	return 0;
}

标签:node,1097,15,int,list,甲级,PAT,data,first
来源: https://blog.csdn.net/zerohawk/article/details/113600161