http://www.patest.cn/contests/pat-a-practise/1097
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年春季的研究生入学考试复试时的机试题,链接 http://www.patest.cn/contests/graduate-entrance-exam-2015-03-20
1. 遇到-1就说明链表结束了,剩余未用的节点无法使用,是断链部分。
2. hash判重真好使。
3.输出格式略麻烦。
#include<iostream>
struct node
{
int data;
int next;
int flag;//标记 1绝对值首次出现,有效 2重复,无效 0不在链表上
}nodeinfo[]; int absolute[]={},value0=;
int headtrue=-,headfalse=-;
int numtrue=-,numfalse=-; int main()
{
for(int i=;i<;i++) absolute[i]=;
for(int i=;i<;i++) nodeinfo[i].next=-,nodeinfo[i].flag=; int n,address=,p=;
scanf("%d%d",&p,&n);
for(int i=;i<n;i++)
{
scanf("%d",&address);
scanf("%d%d",&nodeinfo[address].data,&nodeinfo[address].next);
} if(p==-) return ;
else if(n==) { printf("%05d %d -1",p,nodeinfo[p].data);return ;} while(p>=)
{
value0=nodeinfo[p].data;
if(value0<=) value0=-value0; //fabs(temp)
if(absolute[value0]) //绝对值已出现过
{
if(headfalse==-) headfalse=p,numfalse=;
nodeinfo[p].flag=,numfalse++;
}
else
{
if(headtrue==-) headtrue=p,numtrue=;
absolute[value0]=,nodeinfo[p].flag=,numtrue++;
} p=nodeinfo[p].next;
} int num=;
for(int k=;k<=;k++)
{
if(k==) p=headtrue,num=numtrue-;
else p=headfalse,num=numfalse-; for(int i=;i<=num;i++)
{ if(i) printf(" %05d\n",p);
if(i<num) printf("%05d %d",p,nodeinfo[p].data);
else printf("%05d %d -1\n",p,nodeinfo[p].data); p=nodeinfo[p].next;
while(i<num && nodeinfo[p].flag!=k)
p=nodeinfo[p].next;
}
} return ;
}