PAT(Advanced Level)A1097. Deduplication on a Linked List

题意

删除链表中的值的绝对值重复的结点,以此将链表拆分为2条

思路

  • 静态链表存储方式
  • 开一个unordered_map<int, int>来统计绝对值一样的结点之前是否有出现过

代码

#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <unordered_map>
using namespace std;
struct node {
    int id, key, next;
}link_list[100100];
vector<node> v1, v2;
unordered_map<int, int> first_cur;
int main() {
    int st, num;
    scanf("%d %d", &st, &num);
    int id, key, next;
    for(int i = 1; i <= num; i++) {
        scanf("%d%d%d", &id, &key, &next);
        link_list[id] = node{id, key, next};
    }
    int cur = st;
    while(cur != -1) {
        id = link_list[cur].id;
        key = link_list[cur].key;
        next = link_list[cur].next;
        if(first_cur[abs(key)] == 0) {
            first_cur[abs(key)]++;
            v1.emplace_back(node{id, key, next});
        }else {
            v2.emplace_back(node{id, key, next});
        }
        cur = next;
    }
    for(int i = 0; i < v1.size() - 1; i++) {
        printf("%05d %d %05d\n", v1[i].id, v1[i].key, v1[i + 1].id);
    }
    printf("%05d %d %d\n", v1.back().id, v1.back().key, -1);
    
    if(v2.size() == 0) return 0;
    for(int i = 0; i < v2.size() - 1; i++) {
        printf("%05d %d %05d\n", v2[i].id, v2[i].key, v2[i + 1].id);
    }
    printf("%05d %d %d", v2.back().id, v2.back().key, -1);
    return 0;
}
posted @ 2021-03-16 10:02  MartinLwx  阅读(16)  评论(0编辑  收藏  举报