PAT (Basic Level) Practice (中文)1075 链表元素分类(C语言)
2019-01-20 20:36
731 查看
程序员入门水平,贴出代码大家一起进步!
题目
给定一个单链表,请编写程序将链表元素进行分类排列,使得所有负值元素都排在非负值元素的前面,而 [0, K] 区间内的元素都排在大于 K 的元素前面。但每一类内部元素的顺序是不能改变的。例如:给定链表为 18→7→-4→0→5→-6→10→11→-2,K 为 10,则输出应该为 -4→-6→-2→7→0→5→10→18→11。
输入格式:
每个输入包含一个测试用例。每个测试用例第 1 行给出:第 1 个结点的地址;结点总个数,即正整数N (≤10^5 );以及正整数K (≤10^3 )。结点的地址是 5 位非负整数,NULL 地址用 −1 表示。
接下来有 N 行,每行格式为:
Address Data Next
其中 Address 是结点地址;Data 是该结点保存的数据,为 [−10
5
,10
5
] 区间内的整数;Next 是下一结点的地址。题目保证给出的链表不为空。
输出格式:
对每个测试用例,按链表从头到尾的顺序输出重排后的结果链表,其上每个结点占一行,格式与输入相同。
输入样例:
00100 9 10
23333 10 27777
00000 0 99999
00100 18 12309
68237 -6 23333
33218 -4 00000
48652 -2 -1
99999 5 68237
27777 11 48652
12309 7 33218
输出样例:
33218 -4 68237
68237 -6 48652
48652 -2 12309
12309 7 00000
00000 0 99999
99999 5 23333
23333 10 00100
00100 18 27777
27777 11 -1
思路||总结
- 用静态数组存放,在相应的位置存放相应的数字和下地址,用结构体的话容易超时。
- 分类统计三类数值的数目,因为有无效的节点,所以应以-1作为结束标志,不能以N为节点数目,测试点4就是针对这个。
- 通过统计三类书数值的数量确定其起始位置。
- 按照顺序遍历节点,并将其分类存放,然后将存放的节点顺序输出即可。
AC代码
#include <stdio.h> #include <stdlib.h> typedef struct { int adder; int num; }node; int main() { int i,j,adder,N,K,n1=0,n2=0,n3=0; scanf("%d %d %d",&adder,&N,&K); int num[100010][2]={0};//数值,下一个地址。 for(i=0;i<N;i++) { int t; scanf("%d",&t); scanf("%d %d",&num[t][0],&num[t][1]); }; int t=adder; while(t!=-1)//统计有效数字。 { if(num[t][0]<0)n1++; else if(num[t][0]>=0&&num[t][0]<=K)n2++; else n3++; t=num[t][1]; }; N=n1+n2+n3;//测试点4有无效的节点。 node a ; n3=n2+n1;//三类数字开始存放的节点。 n2=n1; n1=0; while(adder!=-1) { if(num[adder][0]<0) { a[n1].adder=adder; a[n1].num=num[adder][0]; n1++; } else if(num[adder][0]>=0&&num[adder][0]<=K) { a[n2].adder=adder; a[n2].num=num[adder][0]; n2++; } else { a[n3].adder=adder; a[n3].num=num[adder][0]; n3++; } adder=num[adder][1];//下一个节点地址。 }; for(i=0;i<N-1;i++)printf("%05d %d %05d\n",a[i].adder,a[i].num,a[i+1].adder); printf("%05d %d %d\n",a[i].adder,a[i].num,-1);//最后节点下地址为-1特殊输出。 return 0; }
相关文章推荐
- PAT (Basic Level) Practise (中文)1075. 链表元素分类(25)
- PAT (Basic Level) Practise (中文) 1075. 链表元素分类(25)
- PAT basic-level 1075 链表元素分类 笔记
- PAT (Basic Level) Practice (中文)1089 狼人杀-简单版(C语言)
- PAT (Basic Level) Practice (中文)1085 PAT单位排行(C语言)
- 1075 链表元素分类 PAT(B) C语言
- PAT 1075链表元素的分类代码实现及错误分析(C语言)
- PAT (Basic Level) Practice (中文)1086 就不告诉你(C语言)
- PAT (Basic Level) Practice (中文)1078 字符串压缩与解压(C语言)
- PAT (Basic Level) Practice (中文)1087 有多少不同的值(C语言)
- PAT (Basic Level) Practise (中文)1012. 数字分类 (20) C语言
- PAT (Basic Level) Practise (中文)1025. 反转链表 (25)C语言
- PAT (Basic Level) Practice (中文)1079 延迟的回文数(C语言)
- PAT (Basic Level) Practice (中文)1077 互评成绩计算(C语言)
- PAT (Basic Level) Practice (中文)1080 MOOC期终成绩(C语言)
- PAT (Basic Level) Practice (中文)1081 检查密码(C语言)
- PAT (Basic Level) Practice (中文)1082 射击比赛(C语言)
- PAT (Basic Level) Practice (中文)1088 三人行(C语言)
- PAT (Basic Level) Practise (中文)1001. 害死人不偿命的(3n+1)猜想 (15) C语言
- PAT (Basic Level) Practise (中文)1007. 素数对猜想 (20) C语言