7-8 鏈表去重(25 分)

給定一個帶整數鍵值的鏈表 L,你須要把其中絕對值重複的鍵值結點刪掉。即對每一個鍵值 K,
只有第一個絕對值等於 K 的結點被保留。同時,全部被刪除的結點須被保存在另外一個鏈表上。
例如給定 L 爲 21→-15→-15→-7→15,你須要輸出去重後的鏈表 21→-15→-7,還有被刪除的鏈表 -15→15。node

輸入格式:
輸入在第一行給出 L 的第一個結點的地址和一個正整數 N(≤10^​5,爲結點總數)。一個結點的地址是非負的 5 位整數,空地址 NULL 用 -1 來表示。ios

隨後 N 行,每行按如下格式描述一個結點:數組

地址    鍵值    下一個結點spa


其中地址是該結點的地址,鍵值是絕對值不超過10^4​​ 的整數,下一個結點是下個結點的地址。code

輸出格式:
首先輸出去重後的鏈表,而後輸出被刪除的鏈表。每一個結點佔一行,按輸入的格式輸出。string

輸入樣例:
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
 it

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
struct node{
    int data;
    int next;
}list[100005];
int main()
{
    int head, n;
    scanf("%d%d",&head,&n);
    while(n--)
    {
        int adress;
        scanf("%d",&adress);
        scanf("%d%d",&list[adress].data,&list[adress].next);
    }
    int ans[100005], k1 = 0;
    int res[100005], k2 = 0;
    bool vis[100005];
    memset(vis, 0, sizeof(vis));    //把bool類型的數組全值爲0
    int p = head;                   //找到頭節點
    while(p != -1)
    {
        int m = abs(list[p].data);
        if(!vis[m])                 //把數據域出現的數放在vis數組中下標爲m所對應的值中,記錄下來置爲1
        {                           //同把這個地址p存進ans中,而後比較,有重複的話就把這個地址p放到res數組中
            ans[k1++] = p;
            vis[m] = 1;
        }
        else
        {
            res[k2++] = p;
        }
        p = list[p].next;
    }
    printf("%05d", head);
    for(int i = 1; i < k1; i++)
    {
        printf(" %d %05d\n%05d", list[ans[i-1]].data, ans[i], ans[i]);
    }
    printf(" %d -1\n", list[ans[k1-1]].data);
    if(k2 > 0)
    {
        printf("%05d", res[0]);
        for(int i = 1; i < k2; i++)
        {
            printf(" %d %05d\n%05d", list[res[i-1]].data, res[i], res[i]);
        }
        printf(" %d -1", list[res[k2-1]].data);
    }
    return 0;
}