A1097 Deduplication on a Linked List (25分)

血红的双手。 提交于 2020-02-05 15:56:48

一、技术总结

  1. 这一题首先设计数据结构链接结点,除了基本的地址address、数据data和指针next参数,还要一般设计一个order参数,用于记录有效结点,顺便用于满足题目要求。
  2. 设计exist数组存放是否重复出现的数字
  3. 关键点在于直接对于order的区分,重复数字之后的从maxn开始赋值,最后通过sort排序,然后输出。
  4. 然后不用考虑,下一个结点的问题,直接下个结点的地址,直接就是这个结点的指针,打印输出即可。

二、参考代码

#include<cstdlib>
#include<algorithm>
#include<iostream>
#include<cstdio>
using namespace std;
const int maxn = 100010;
struct Node{
    int address;
    int data;
    int next;
    int order = 2*maxn; 
}node[maxn];
bool exist[maxn] = {false};
bool cmp(Node a, Node b){
    return a.order < b.order;
}
int main(){
    int head, n, cnt1 = 0, cnt2 = 0;
    scanf("%d%d", &head, &n);
    int address;
    for(int i = 0; i < n; i++){
        scanf("%d", &address);
        scanf("%d%d", &node[address].data, &node[address].next);
        node[address].address = address;
    }
    for(int i = head; i != -1; i = node[i].next){
        if(exist[abs(node[i].data)] == false){
            exist[abs(node[i].data)] = true;
            node[i].order = cnt1++;
        }else{
            node[i].order = maxn + cnt2;
            cnt2++;
        }
    }
    sort(node, node+maxn, cmp);
    int cnt = cnt1 + cnt2;
    for(int i = 0; i < cnt; i++){
        if(i != cnt1-1 && i != cnt-1){
            printf("%05d %d %05d\n", node[i].address, node[i].data, node[i+1].address);
        }else{
            printf("%05d %d -1\n", node[i].address, node[i].data);
        }
    }
    return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!