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.输出格式略麻烦。
1 #include<iostream> 2 struct node 3 { 4 int data; 5 int next; 6 int flag;//标记 1绝对值首次出现,有效 2重复,无效 0不在链表上 7 }nodeinfo[100010]; 8 9 int absolute[10010]={0},value0=0; 10 int headtrue=-1,headfalse=-1; 11 int numtrue=-1,numfalse=-1; 12 13 int main() 14 { 15 for(int i=0;i<10010;i++) absolute[i]=0; 16 for(int i=0;i<100010;i++) nodeinfo[i].next=-1,nodeinfo[i].flag=0; 17 18 int n,address=0,p=0; 19 scanf("%d%d",&p,&n); 20 for(int i=0;i<n;i++) 21 { 22 scanf("%d",&address); 23 scanf("%d%d",&nodeinfo[address].data,&nodeinfo[address].next); 24 } 25 26 if(p==-1) return 0; 27 else if(n==1) { printf("%05d %d -1",p,nodeinfo[p].data);return 0;} 28 29 while(p>=0) 30 { 31 value0=nodeinfo[p].data; 32 if(value0<=0) value0=0-value0; //fabs(temp) 33 if(absolute[value0]) //绝对值已出现过 34 { 35 if(headfalse==-1) headfalse=p,numfalse=0; 36 nodeinfo[p].flag=2,numfalse++; 37 } 38 else 39 { 40 if(headtrue==-1) headtrue=p,numtrue=0; 41 absolute[value0]=1,nodeinfo[p].flag=1,numtrue++; 42 } 43 44 p=nodeinfo[p].next; 45 } 46 47 48 49 int num=0; 50 for(int k=1;k<=2;k++) 51 { 52 if(k==1) p=headtrue,num=numtrue-1; 53 else p=headfalse,num=numfalse-1; 54 55 for(int i=0;i<=num;i++) 56 { 57 58 if(i) printf(" %05d ",p); 59 if(i<num) printf("%05d %d",p,nodeinfo[p].data); 60 else printf("%05d %d -1 ",p,nodeinfo[p].data); 61 62 p=nodeinfo[p].next; 63 while(i<num && nodeinfo[p].flag!=k) 64 p=nodeinfo[p].next; 65 } 66 } 67 68 69 70 return 0; 71 } 72 73 74