当前位置: 代码迷 >> 综合 >> 1075 链表元素分类 PAT(B) C语言
  详细解决方案

1075 链表元素分类 PAT(B) C语言

热度:7   发布时间:2024-01-06 15:55:36.0


  题目链接:https://www.patest.cn/contests/pat-b-practise/1075


给定一个单链表,请编写程序将链表元素进行分类排列,使得所有负值元素都排在非负值元素的前面,而[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行给出:第1个结点的地址;结点总个数,即正整数N (<= 105);以及正整数K (<=1000)。结点的地址是5位非负整数,NULL地址用-1表示。

接下来有N行,每行格式为:

Address Data Next

其中Address是结点地址;Data是该结点保存的数据,为[-105, 105]区间内的整数;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

思路:定义了结构体存储节点,题目说地址为5位,简单暴力地用一个100000的node数组来存放数据,遍历三次,第一次输出小于0的节点,第二次输出[0-K]的节点,第三次输出大于K的节点。 每轮循环的输出顺序为  当前结点地址----换行----当前结点地址----当前结点data。要注意判断一下当前输出是否为第一次输出,如果是第一次输出则只输出当前结点地址----当前结点data,然后下一轮。注意空格的输出位置。

这么简单的思路考试的时候居然没做出来。。


#include<stdio.h>
#include<stdlib.h>#define ElemType int
typedef struct{ElemType data;int cur;
}node,component;int main(){int first,N,K,i,j;int t1,t2,t3;int isshuchu=0;scanf("%d %d %d",&first,&N,&K);node nodes[100000];//node *nodes=(node*)malloc(100000*sizeof(nodes[0]));for(i=0;i<N;i++){scanf("%d %d %d",&t1,&t2,&t3);nodes[t1].data=t2;nodes[t1].cur=t3;}i=first;while(i!=-1){if(nodes[i].data<0){if(isshuchu==1){printf(" %05d\n",i);isshuchu=1;}printf("%05d %d",i,nodes[i].data);isshuchu=1;}i=nodes[i].cur;}i=first;while(i!=-1){if(nodes[i].data>=0&&nodes[i].data<=K){if(isshuchu==1){printf(" %05d\n",i);isshuchu=1;}printf("%05d %d",i,nodes[i].data);isshuchu=1;}i=nodes[i].cur;}i=first;while(i!=-1){if(nodes[i].data>K){if(isshuchu==1){printf(" %05d\n",i);isshuchu=1;}printf("%05d %d",i,nodes[i].data);isshuchu=1;}i=nodes[i].cur;}printf(" -1");return 0;
}