PAT (Advanced Level) Practice 1097 Deduplication on a Linked List(25分)

Given a singly linked list LL with integer keys, you are supposed to remove the nodes with duplicated absolute values of the keys. That is, for each value K K K, only the first node of which the value or absolute value of its key equals K K K will be kept. At the mean time, all the removed nodes must be kept in a separate list. For example, given L L L being 21 → − 15 → − 15 → − 7 → 15 21→-15→-15→-7→15 211515715, you must output 21 → − 15 → − 7 21→-15→-7 21157, and the removed list − 15 → 15 -15→15 1515.

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   ( ≤ 1 0 5 ) N \ (≤10^5) 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 N 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 KaTeX parse error: Expected group after '^' at position 3: 10^̲, 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 5
99999 -7 87654
23854 -15 00000
87654 15 -1
00000 -15 99999
00100 21 23854

Sample Output:

00100 21 23854
23854 -15 99999
99999 -7 -1
00000 -15 87654
87654 15 -1

题意

给出一个链表,删除这个链表中的一些结点,使得每个结点的值的绝对值是唯一的。输出修改后的链表和删除的结点组成的链表。

思路

遍历一遍链表,用 pre 指向当前位置的前驱,方便删除操作。将删除的结点按照顺序放到 removed 中。

代码

#include 
#include 
#include 
#include 

using namespace std;

struct node {
    int address, data, next;
} nodes[100005];

set<int> values;
vector<node> removed;

int main() {
    int head, n, addr;
    cin >> head >> n;

    for (int i = 0; i < n; ++i) {
        cin >> addr;
        nodes[addr].address = addr;
        cin >> nodes[addr].data >> nodes[addr].next;
    }

    for (int iter = head, pre = -1; iter != -1; iter = nodes[iter].next) {
        if (values.count(abs(nodes[iter].data))) {
            if (pre != -1) nodes[pre].next = nodes[iter].next;
            removed.push_back(nodes[iter]);
        }
        else {
            pre = iter;
            values.insert(abs(nodes[iter].data));
        }
    }

    if (head == -1) printf("-1\n");
    else {
        for (int iter = head; iter != -1; iter = nodes[iter].next) {
            printf("%05d %d ", nodes[iter].address, nodes[iter].data);
            if (nodes[iter].next == -1) printf("-1\n");
            else printf("%05d\n", nodes[iter].next);
        }
        for (int i = 0, size = removed.size(); i < size; ++i) {
            printf("%05d %d ", removed[i].address, removed[i].data);
            if (i == size - 1) printf("-1\n"); 
            else printf("%05d\n", removed[i + 1].address);
        }
    }
}

你可能感兴趣的:(PAT)