PAT L2-002. 链表去重 模拟

题目链接:https://www.patest.cn/contests/gplt/L2-002

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>

using namespace std;

#define INF 0x3f3f3f3f
#define N 100005
typedef long long ll;


int firstAddress[10005];
int key[N];
int next[N];
bool duplicate[N]={false};

int main()
{
    int s,n;
    scanf("%d%d",&s,&n);
    memset(firstAddress,-1,sizeof firstAddress);
    for(int i=0;i<n;i++){
        int a,k,n;
        scanf("%d%d%d",&a,&k,&n);
        key[a]=k;
        next[a]=n;

    }
    int a=s; int s1=-1;
    while(a!=-1){ //检测结点是否为重复的
        if(firstAddress[abs(key[a])]==-1)
            firstAddress[abs(key[a])]=a;
        else{
            duplicate[a]=true;
            if(s1==-1) s1=a;
        }
        a=next[a];
    }
    a=s;
    int lastFalse=-1,lastTrue=-1;
    while(a!=-1){ //因为是向前更新指针,所以在对链表向后遍历的时候并不会断节
        if(!duplicate[a]){
            if(lastFalse!=-1)
                next[lastFalse]=a;
            lastFalse=a;
        }
        else{
            if(lastTrue!=-1)
                next[lastTrue]=a;
            lastTrue=a;
        }
        a=next[a];
    }
    next[lastFalse]=-1; next[lastTrue]=-1;
    a=s;
    while(a!=-1){
        printf("%05d %d ",a,key[a]);
        if(next[a]==-1)
            printf("-1\n");
        else
            printf("%05d\n",next[a]);
        a=next[a];
    }
    a=s1;
    while(a!=-1){
        printf("%05d %d ",a,key[a]);
        if(next[a]==-1)
            printf("-1\n");
        else
            printf("%05d\n",next[a]);
        a=next[a];
    }
    return 0;
}

PAT上的编译器不允许用next变量名,换一个名称就行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值