【PAT】1097. Deduplication on a Linked List (25)

时间:2020-12-21 19:47:26

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 (<= 105) 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 104, 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

题意:模拟链表的操作。把一个链表中绝对值重复的节点剔除出来形成一个新的链表,分别输出俩个链表。

分析:首先构建链表,然后只要用俩个vector分别存储这俩个链表,然后输出就可以了。

代码如下:

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

struct node{
	int addr;
	int key;
	int next;
};

int main(int argc, char** argv) {
	int root, n, i;
	scanf("%d%d",&root, &n);
	vector<node> list(100000);
	
	int addr, key, next;
	for(i=0; i<n; i++){
		scanf("%d %d %d",&addr,&key,&next);
		list[addr].key = key;
		list[addr].next = next;	
		list[addr].addr = addr;
	}
	
	if(list[root].addr == -1){
		cout<<endl;
		return 0;
	}
	
	vector<int> flag(10001,-1);
	vector<node> cut; //存放因为重复而被删掉的节点 
	vector<node> vec;
	int index = root;
	while( index != -1){
		key = abs(list[index].key);
		if(flag[key] == -1){
			flag[key] = 1;
			vec.push_back(list[index]);
		}else{
			cut.push_back(list[index]);
		}	
		index = list[index].next;	
	}
	
	node Node;
	for(i=0; i<vec.size()-1; i++){
		Node = vec[i];
		printf("%05d %d %05d\n", Node.addr, Node.key, vec[i+1].addr );		
	}
	Node = vec[vec.size()-1];
	printf("%05d %d -1\n", Node.addr, Node.key );
 	
	//没有重复的情况下	
 	if(cut.size() == 0)
 		return 0;
	for(i=0; i<cut.size()-1; i++){
		Node = cut[i];
		printf("%05d %d %05d\n", Node.addr, Node.key, cut[i+1].addr );		
	}
	Node = cut[cut.size()-1];
	printf("%05d %d -1\n", Node.addr, Node.key );
	
	return 0;
}