算法思想:
根据题意分三步走 :遍历链表,①将遇到的负数的下标记录在out1数组中 ;
②将遇到【0,K】内的链表元素的下标记录在out2数组中;
③将其他元素的下标记录在out3数组中 ;
最后按out1,out2,out3数组下标输出链表元素即可。
注意点:输出格式(详见代码)。
题目与代码:
给定一个单链表,请编写程序将链表元素进行分类排列,使得所有负值元素都排在非负值元素的前面,而 [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 (≤105);以及正整数K (≤103)。结点的地址是 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
/***************2019.6.20-13:05-13:25(完成思想)**************/
/***************2019.6.21-12:40-13:28(实现中)**************/
/***************2019.6.22-12:40-12:54(fininshed)**************/
//B1075 链表元素分类 1.2h
//算法思想: 根据题意分三步走 :遍历链表,①将遇到的负数的下标记录在out1数组中 ;
// ②将遇到【0,K】内的链表元素的下标记录在out2数组中;
// ③将其他元素的下标记录在out3数组中 ;
// 最后按out1,out2,out3数组下标输出即可。
#include<iostream>
//typedef struct node *ListNode;
struct node{
int data;
int next;
}List[100000];
int main(){
int i;
int begin,N,K;
scanf("%d%d%d",&begin,&N,&K);
int A,D,Ne;
for(i=0;i<N;i++){
scanf("%d%d%d",&A,&D,&Ne);
List[A].data=D;
List[A].next=Ne;
}
int p=0,q=0,r=0,out1[100000],out2[100000],out3[100000];
A=begin;
do {
D=List[A].data;
if(D<0) out1[p++]=A;//①
else if(D>=0&&D<=K) out2[q++]=A;//②
else out3[r++]=A;
A=List[A].next;
}while(A!=-1);
for(i=0;i<p;i++){
printf("%05d %d ",out1[i],List[out1[i]].data);
if(i<p-1) printf("%05d\n",out1[i+1]);
}
for(i=0;i<q;i++){
if(p!=0&&i==0) printf("%05d\n",out2[i]); //注意判断条件
printf("%05d %d ",out2[i],List[out2[i]].data);
if(i<q-1) printf("%05d\n",out2[i+1]);
}
for(i=0;i<r;i++){
if((p!=0||q!=0)&&i==0) printf("%05d\n",out3[i]); //注意判断条件
printf("%05d %d ",out3[i],List[out3[i]].data);
if(i<r-1) printf("%05d\n",out3[i+1]);
}
printf("-1\n");
return 0;
}