1097 Deduplication on a Linked List

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

absolute value
英[ˈæbsəluːt ˈvæljuː]
美[ˈæbsəluːt ˈvæljuː]
[词典] 内在价值;绝对值;

duplicated
英[ˈdjuːplɪkeɪtɪd]
美[ˈduːplɪkeɪtɪd]
v. 复制; 复印; 复写; (尤指不必要时) 重复,再做一次;
不难,难在理解意思吧,这两个生词,
我写的比较臃肿,其实分别用三个数组存地址,值,next就好,我这么写是我个人习惯或者比较好写

#include<cstdio>
#include<algorithm>
#include<iostream>
const int N=1e6+5;
using namespace std; 
struct node{
	int date,address,next;
};
bool bk[N]={false};
node NNode[N],NNNode[N],Node[N],dele[N];
int main(){
	int s,n,add,data,next;
	cin>>s>>n;
	for(int i=0;i<n;i++){
		cin>>add>>data>>next;
		NNNode[add].address=add;
		NNNode[add].date=data;
		NNNode[add].next=next;
	}
	int w=0;
	while(s!=-1){
		NNode[w].address=s;
		NNode[w].date=NNNode[s].date;
		w++;
		s=NNNode[s].next;
	}
	int j=0,d=0;
	for(int i=0;i<w;i++){
		if(!bk[ abs(NNode[i].date ) ]){
			bk[ abs(NNode[i].date) ]=true;
			Node[j].address=NNode[i].address;
			Node[j].date=NNode[i].date;
			j++; 
		}
		else{
			dele[d].address=NNode[i].address;
			dele[d].date=NNode[i].date;
			d++;
		}
	}
	for(int i=0;i<j;i++){
		if(i<j-1) printf("%05d %d %05d\n",Node[i].address,Node[i].date,Node[i+1].address);
		else printf("%05d %d -1\n",Node[i].address,Node[i].date);
	}
	for(int i=0;i<d;i++){
		if(i<d-1) printf("%05d %d %05d\n",dele[i].address,dele[i].date,dele[i+1].address);
		else printf("%05d %d -1",dele[i].address,dele[i].date);
	}
	return 0;
}
发布了139 篇原创文章 · 获赞 3 · 访问量 8495

猜你喜欢

转载自blog.csdn.net/weixin_44270812/article/details/103178077