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数组中,移除的元素放到里一个vector中,最后顺序输出这两个vector即可,链表判别是否重复可以使用哈希表。
参考代码:
#include<cstdio>
#include<vector>
#include<cmath>
using namespace std;
int n,st,hasht[10010];
struct node{
int addr,data,next;
}list[100010],t;
vector<node> ans,removed;
int main()
{
scanf("%d%d",&st,&n);
int p=st,addr;
for(int i=0;i<n;i++){
scanf("%d",&addr);
scanf("%d%d",&list[addr].data,&list[addr].next);
list[addr].addr=addr;
}
while(p!=-1){
int data=abs(list[p].data);
if(hasht[data]==0){
hasht[data]=1;
ans.push_back(list[p]);
}else
removed.push_back(list[p]);
p=list[p].next;
}
printf("%05d %d",ans[0].addr,ans[0].data);
for(int i=1;i<ans.size();i++){
printf(" %05d\n%05d %d",ans[i].addr,ans[i].addr,ans[i].data);
}
printf(" -1\n");
if(removed.size()==0) return 0;
printf("%05d %d",removed[0].addr,removed[0].data);
for(int i=1;i<removed.size();i++){
printf(" %05d\n%05d %d",removed[i].addr,removed[i].addr,removed[i].data);
}
printf(" -1\n");
return 0;
}