【1008Deduplication on a Linked List (25)】+ 链表

来源:互联网 发布:微淘加粉软件 编辑:程序博客网 时间:2024/06/07 05:35

题目描述
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.

输入描述:
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.

输出描述:
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.

输入例子:
00100 5
99999 -7 87654
23854 -15 00000
87654 15 -1
00000 -15 99999
00100 21 23854

输出例子:
00100 21 23854
23854 -15 99999
99999 -7 -1
00000 -15 87654
87654 15 -1

题意 : 给出一串连续的链表,去掉 abs(id) 重复的节点,并输出他们

思路 : 很明显的链表,把重复的筛选出来放在一起,每次的s[i].z 由 s[i + 1].x 替代

AC代码:

#include<cstdio>#include<cmath>#include<cstring>#include<algorithm>using namespace std;const int MAX = 1e5 + 10;typedef long long LL;struct node{    int x,y,z;}s[MAX],st[MAX],ss[MAX];int m[MAX];int main(){    int a,n,x,y,z;    while(~scanf("%d %d",&a,&n)){        memset(m,0,sizeof m);        int nl = 0,nr = 0;        for(int i = 0; i < n; i++){            scanf("%d %d %d",&x,&y,&z);            s[x].x = x,s[x].y = y,s[x].z = z;        }        while(a != -1){            if(!m[abs(s[a].y)]){                m[abs(s[a].y)] = 1;                st[++nl] = s[a];            }            else ss[++nr] = s[a];            a = s[a].z;        }        if(nl){            for(int i = 1; i < nl; i++)                printf("%05d %d %05d\n",st[i].x,st[i].y,st[i + 1].x);            printf("%05d %d -1\n",st[nl].x,st[nl].y);        }        if(nr){            for(int i = 1; i < nr; i++)                printf("%05d %d %05d\n",ss[i].x,ss[i].y,ss[i + 1].x);            printf("%05d %d -1\n",ss[nr].x,ss[nr].y);        }    }    return 0;}