L2-002. 链表去重

给定一个带整数键值的单链表L,本题要求你编写程序,删除那些键值的绝对值有重复的结点。即对任意键值K,只有键值或其绝对值等于K的第一个结点可以被保留。同时,所有被删除的结点必须被保存在另外一个链表中。例如:另L为21→-15→-15→-7→15,则你必须输出去重后的链表21→-15→-7、以及被删除的链表-15→15。

输入格式:

输入第一行包含链表第一个结点的地址、以及结点个数N(<= 105 的正整数)。结点地址是一个非负的5位整数,NULL指针用-1表示。

随后N行,每行按下列格式给出一个结点的信息:

Address Key Next

其中Address是结点的地址,Key是绝对值不超过104的整数,Next是下一个结点的地址。

输出格式:

首先输出去重后的链表,然后输出被删除结点组成的链表。每个结点占一行,按输入的格式输出。

输入样例:

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
#include<algorithm>
#include<iostream>
#include<cstdio>
#include<set>

using namespace std;
const int N = 1e5 + 5;
const int INF = (1 << 30);

struct node{
    int key, next;
    node(){ next = -1; }
}Node[N];

int n;
node head, ans;
void print(int s){
    int p = s;
    while(p != -1){
        printf("%05d %d ", p, Node[p].key);
        if(Node[p].next == -1) printf("-1
");
        else printf("%05d
", Node[p].next);
        p = Node[p].next;
    }
}
bool flag[N];

void Work(){
    fill(flag, flag + N, false);
    int p = head.next;
    int tail = -1, last = -1; //head, ans
    while(p != -1){
        int tmp = Node[p].key;
        if(flag[abs(tmp)]){
            if(last == -1) ans.next = p;
            else Node[last].next = p;
            last = p;
        }else{
            flag[abs(tmp)] = true;
            if(tail == -1) head.next = p;
            else Node[tail].next = p;
            tail = p;
        }
        p = Node[p].next;
    }
    Node[tail].next = -1;
    Node[last].next = -1;
    print(head.next);
    print(ans.next);
}
int main(){
    int add, key, next;
    scanf("%d %d", &head.next, &n);
    if(n == 0) return 0;
    for(int i = 0; i < n; i++){
        scanf("%d %d %d", &add, &key, &next);
        Node[add].key = key;
        Node[add].next = next;
    }
    //print(head.next);
    Work();
}
原文地址:https://www.cnblogs.com/Pretty9/p/8620657.html