您的位置:首页 > 其它

PAT (Advanced Level) 1097. Deduplication on a Linked List (25) 链表去重

2015-08-01 09:35 531 查看
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

使用一个哈希表判断数字是否重复出现。将第一次出现的和重复出现的数字分别连同其地址一起压入两个不同的数组。
/*2015.8.1cyq*/
#include <iostream>
#include <vector>
#include <fstream>
#include <math.h>
using namespace std;

//ifstream fin("case1.txt");
//#define cin fin

struct node{
int addr;
int key;
int next;
node(){}
node(int a,int k,int n):addr(a),key(k),next(n){}
};

int main(){
int head,N;
cin>>head>>N;
vector<bool> visited(10000,false);
vector<node> L(100000);
vector<node> L1,L2;
int x;
for(int i=0;i<N;i++){
cin>>x;
L[x].addr=x;
cin>>L[x].key;
cin>>L[x].next;
}
int p=head;
while(p!=-1){
if(!visited[abs(L[p].key)]){
visited[abs(L[p].key)]=true;
L1.push_back(L[p]);
}else
L2.push_back(L[p]);
p=L[p].next;
}
int n1=L1.size();
int n2=L2.size();
//修改next并输出
for(int i=0;i<n1-1;i++){
L1[i].next=L1[i+1].addr;
printf("%05d %d %05d\n",L1[i].addr,L1[i].key,L1[i].next);
}
if(n1>0){
L1[n1-1].next=-1;
printf("%05d %d %d\n",L1[n1-1].addr,L1[n1-1].key,L1[n1-1].next);
}

for(int i=0;i<n2-1;i++){
L2[i].next=L2[i+1].addr;
printf("%05d %d %05d\n",L2[i].addr,L2[i].key,L2[i].next);
}
if(n2>0){
L2[n2-1].next=-1;
printf("%05d %d %d\n",L2[n2-1].addr,L2[n2-1].key,L2[n2-1].next);
}
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: