1097. Deduplication on a Linked List (25)

来源:互联网 发布:淘宝新店如何做起来 编辑:程序博客网 时间:2024/05/16 00:27

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 599999 -7 8765423854 -15 0000087654 15 -100000 -15 9999900100 21 23854
Sample Output:
00100 21 2385423854 -15 9999999999 -7 -100000 -15 8765487654 15 -1
-----------------------华丽的分割线------------------------
分析:可以用一个数组来存输入,然后创建两个向量分别存result和removed,最后输出就好。
代码:
#include <cstdio>#include <cstdlib>#include <cmath>#include <vector>using namespace std;#define MaxNumOfNode 100001#define MaxNumOfKey 10001typedef struct{int key;int next;}Node;bool visited[MaxNumOfKey];Node input[MaxNumOfNode];vector<int> result;vector<int> removed;int main(void){int header,N;scanf("%5d %d\n",&header,&N);int i,inaddr,inkey,innext;for(i=0;i<N;++i){scanf("%5d %d %d",&inaddr,&inkey,&innext);input[inaddr].key = inkey;input[inaddr].next = innext;}int thisnode = header;int value;while(thisnode != -1){value = abs(input[thisnode].key);if(!visited[value]){visited[value] = true;result.push_back(thisnode);}else{removed.push_back(thisnode);}thisnode = input[thisnode].next;}bool first = false;for(i=0;i<result.size();++i){if(!first){printf("%05d %d",result[i],input[result[i]].key);first = true;}else{printf(" %05d\n",result[i]);printf("%05d %d",result[i],input[result[i]].key);}if(i==result.size()-1)printf(" -1\n");}first = false;for(i=0;i<removed.size();++i){if(!first){printf("%05d %d",removed[i],input[removed[i]].key);first = true;}else{printf(" %05d\n",removed[i]);printf("%05d %d",removed[i],input[removed[i]].key);}if(i==removed.size()-1)printf(" -1\n");}system("pause");return 0;}


0 0
原创粉丝点击