1-10 链表去重 (20分)
PTA的链接
L2-002 链表去重 (25分)
给定一个带整数键值的链表 L,你需要把其中绝对值重复的键值结点删掉。即对每个键值 K,只有第一个绝对值等于 K 的结点被保留。同时,所有被删除的结点须被保存在另一个链表上。例如给定 L 为 21→-15→-15→-7→15,你需要输出去重后的链表 21→-15→-7,还有被删除的链表 -15→15。
输入格式:
输入在第一行给出 L 的第一个结点的地址和一个正整数 N(≤10e5 ,为结点总数)。一个结点的地址是非负的 5 位整数,空地址 NULL 用 -1 来表示。
随后 N 行,每行按以下格式描述一个结点:
地址 键值 下一个结点
其中地址是该结点的地址,键值是绝对值不超过10e4的整数,下一个结点是下个结点的地址。
输出格式:
首先输出去重后的链表,然后输出被删除的链表。每个结点占一行,按输入的格式输出。
输入样例:
00100 5
99999 -7 87654
23854 -15 00000
87654 15 -1
00000 -15 99999
00100 21 23854
输出样例:
00100 21 23854
23854 -15 99999
99999 -7 -1
00000 -15 87654
87654 15 -1
这是用C语言写的代码,不是我自己写的,我也没有看懂,先保存一下。
PS:33-39行,不是很看的懂???
借鉴来的还是不好啊
AC代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 100000
struct list
{
int date;
int next;
};
int main()
{
int head,n;
int i,j;
int a[MAX]= {0},b[MAX],c[MAX];
int x=0,y=0;
struct list list[MAX];
scanf("%d %d",&head,&n);
for(i=0; i<n; i++)
{
//将第一个位置数字保存下来,作为数组下标
scanf("%d",&j);
scanf("%d %d",&list[j].date,&list[j].next);
}
for(i=head; i!=-1; i=list[i].next)
{//通过i=list[i].next,循环遍历数组,判断是否有绝对值相同的数据
j=list[i].date;
if(j<0)
j=-j;
/*如果已经出现过了该数据,则a[j]就已经被置为1了,
此时将需要删除的元素存入存入数组b中,按照顺序存储*/
if(a[j])
b[x++]=i;
else
{
//若是第一次出现该数据,将标志数组a[j]置为1
//并将不需要删除的数组下标记录在c数组中
a[j]=1;
c[y++]=i;
}
}
//输出
//先输出有数组c存储的不需要删除的元素
for(i=0; i<y; i++)
{
//判断是不是第一个元素,是的话,next值置为-1
if(i==y-1)
printf("%05d %d -1\n",c[i],list[c[i]].date);
else
printf("%05d %d %05d\n",c[i],list[c[i]].date,c[i+1]);
}
//输出b存储的需要删除的元素
for(i=0; i<x; i++)
{
//判断是不是第一个元素,是的话,next值置为-1
if(i==x-1)
printf("%05d %d -1\n",b[i],list[b[i]].date);
else
printf("%05d %d %05d\n",b[i],list[b[i]].date,b[i+1]);
}
return 0;
}
后来写的,正确的啊啊
#include<bits/stdc++.h>
#include <iostream>
#include <algorithm>
using namespace std;
struct stu {
int data;
int next;
};
stu xx[999999];
int main() {
int h,n;
cin>>h>>n;
int a,b,c;
for(int i=0; i<n; i++) {
cin>>a>>b>>c;
xx[a].data=b;
xx[a].next=c;
}
int p[99999]= {0}; //记录该键值是否是第一次遇见
int x[n],y[n];//分别记录 去重后和被删除的链表的地址
int x1=0,y1=0;
for(int i=h; i!=-1; i=xx[i].next) {
int t=xx[i].data;
if(t<0) t=-t;
if(p[t]==0) {//第一次出现
p[t]=1;
x[x1++]=i;
} else y[y1++]=i;
}
for(int i=0; i<x1; i++) {
if(i==x1-1)
printf("%05d %d -1\n",x[i],xx[x[i]].data);
else printf("%05d %d %05d\n",x[i],xx[x[i]].data,x[i+1]);
}
for(int i=0; i<y1; i++) {
if(i==y1-1)
printf("%05d %d -1\n",y[i],xx[y[i]].data);
else printf("%05d %d %05d\n",y[i],xx[y[i]].data,y[i+1]);
}
return 0;
}