PAT-GPLT训练集 L2-002 链表去重

题目大意为给出一个单链表,去除重复的结点,输出删除后的链表,并且把被删除的结点也以链表形式输出

思路:把这个链表直接分成两个链表,再直接输出就可以

代码:

#include<iostream>
#include<cstdio>
#include<set>
#include<cmath>
using namespace std;
const int MAX_N = 100000+5;
typedef struct { int address, key, next; } P;
P a[MAX_N], b[MAX_N], c[MAX_N];

set<int> check; 
int n, s;
int main() {
    cin >> s >> n;
    int from, key, to;
    for(int i = 0; i < n; i++) {
        scanf("%d%d%d", &from, &key, &to);
        a[from].address = from;
        a[from].key = key;
        a[from].next = to;
    }
    int c1 = 0, c2 = 0;
    while(s != -1) {
        if(check.count(abs(a[s].key))) {
            c[c2++] = a[s]; 
        } else {
            check.insert(abs(a[s].key));
            b[c1++] = a[s];    
        }
        s = a[s].next;
    } 
    for(int i = 0; i < c1; i++) {
        if(!i) printf("%05d %d ", b[i].address, b[i].key);
        else printf("%05d\n%05d %d ", b[i].address, b[i].address, b[i].key);
    }
    printf("-1\n");
    for(int i = 0; i < c2; i++) {
        if(!i) printf("%05d %d ", c[i].address, c[i].key);
        else printf("%05d\n%05d %d ", c[i].address, c[i].address, c[i].key);
    }
    if(c2) printf("-1");
    return 0;
}

 

posted on 2018-03-29 11:43  kindleheart  阅读(123)  评论(0编辑  收藏  举报