/*************************
题意:
剔除链表中data重复的节点,并放入一个新的链表
************************/
/***********************
解题思路:
考察链表的插入和删除。
用set去判断是否出现过。
被删除的节点用尾插法插入新链表。
*************************/
/***********************
笔记:
*********************/
#include<iostream>
#include<stdio.h>
#include<string>
#include<vector>
#include<queue>
#include<stdlib.h>
#include<algorithm>
#include<string.h>
#include<stack>
#include<map>
#include<set>
#include<unordered_map>
using namespace std;
#define M 100009
#define INF 0x7ffffff
struct Node{
int addr;
int data;
int addnext;
};
Node node[M];
int main(){
int i, j;
int n, head, addr, data, addnext;
cin>>head>>n;
for(i = 0;i < n;i++){
scanf("%d%d%d",&addr, &data, &addnext);
node[addr].addr = addr;
node[addr].addnext = addnext;
node[addr].data = data;
}
int lastp, q, p = head;
int qhead;
qhead = M+1;
q = qhead;
node[q].addnext = -1;
set<int> s;
while(p != -1){
data = abs(node[p].data);
if(s.find(abs(data)) == s.end()){
s.insert(data);
lastp = p;
p = node[p].addnext;
}
else{
node[lastp].addnext = node[p].addnext;
node[q].addnext = node[p].addr;
node[p].addnext = -1;
q = p; //尾插法
p = node[lastp].addnext;
}
}
p = head;
while(p != -1){
printf("%05d %d ", p, node[p].data);
if(node[p].addnext == -1)
printf("-1\n");
else printf("%05d\n",node[p].addnext);
p = node[p].addnext;
}
p = node[qhead].addnext;
while(p != -1){
printf("%05d %d ", p, node[p].data, node[p].addnext);
if(node[p].addnext == -1)
printf("-1\n");
else printf("%05d\n",node[p].addnext);
p = node[p].addnext;
}
return 0;
}
PAT 1097. Deduplication on a Linked List (25) 剔除链表中的重复节点,set用法,尾插法
最新推荐文章于 2022-11-02 15:31:53 发布