L2-002 链表去重(测试点1的坑)

思路: 通过map映射先将原链表处理出来,再通过判重将其分成两部分存储输出。注意测试点1有个坑点(原链表不是一条完成的链表,数据如下:)

(测试点1)输入:

00001 3

00001 1 00002

00002 2 -1

00003 3 00004 

(测试点1)输出: 

00001 1 00002
00002 2 -1

代码实现: 

#include<bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
const int N = 1e5+10;

int n, b[N], idx, tt, val;
string head, pos, nxt;
map<int, int> vis;
map<string, int> mp;
map<string, string> np;
vector<string> a, ans1, ans2;
int a1[N], a2[N], tt1, tt2, last;

//struct node{
//    int pos, val, next;
//}b[N];

signed main()
{
    cin >> head >> n;
    for(int i = 1; i <= n; i ++){
        cin >> pos >> val >> nxt;
        mp[pos] = val;
        np[pos] = nxt;
        if(pos==head) idx = i;
    }
    a.push_back("0");
    while(tt<n){
        a.push_back(head);
        b[++tt] = mp[head];
        head = np[head];
    }
    for(int i = 1; i <= n; i ++){
//        cout << a[i] << " \n"[i==n];
        if(a[i]=="-1"){
            last = i-1;
            break;
        }
    }
    if(!last) last = n;  //测试点1的坑
//    cout << "last: " << last << endl;
    for(int i = 1; i <= last; i ++){
//        cout << b[i] << " \n"[i==n];
        if(!vis[abs(b[i])]){
            vis[abs(b[i])] = 1;
            ans1.push_back(a[i]);
            a1[tt1++] = b[i];
        }
        else{
            ans2.push_back(a[i]);
            a2[tt2++] = b[i];
        }
    }
    for(int i = 0; i < tt1; i ++){
        if(i==tt1-1) cout << ans1[i] << " " << a1[i] << " " << -1 << endl;
        else cout << ans1[i] << " " << a1[i] << " " << ans1[i+1] << endl;
    }
    for(int i = 0; i < tt2; i ++){
        if(i==tt2-1) cout << ans2[i] << " " << a2[i] << " " << -1 << endl;
        else cout << ans2[i] << " " << a2[i] << " " << ans2[i+1] << endl;
    }

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值