Given a singly linked list, you are supposed to rearrange its elements so that all the negative values appear before all of the non-negatives, and all the values in [0, K] appear before all those greater than K. The order of the elements inside each class must not be changed. For example, given the list being 18→7→-4→0→5→-6→10→11→-2 and K being 10, you must output -4→-6→-2→7→0→5→10→18→11.
给定一个单链表,请编写程序将链表元素进行分类排列,使得所有负值元素都排在非负值元素的前面,而 [0, K] 区间内的元素都排在大于 K 的元素前面。但每一类内部元素的顺序是不能改变的。例如:给定链表为 18→7→-4→0→5→-6→10→11→-2,K 为 10,则输出应该为 -4→-6→-2→7→0→5→10→18→11。
Input Specification:
Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N (≤10^5) which is the total number of nodes, and a positive K (≤10^3). The address of a node is a 5-digit nonnegative integer, and NULL is represented by −1.
每个输入包含一个测试用例。每个测试用例第 1 行给出:第 1 个结点的地址;结点总个数,即正整数N (≤10^5);以及正整数K (≤10^3)。结点的地址是 5 位非负整数,NULL 地址用 −1 表示。
Then N lines follow, each describes a node in the format:
Address Data Next
where Address is the position of the node, Data is an integer in [−10^5,10^5], and Next is the position of the next node. It is guaranteed that the list is not empty.
其中 Address 是结点地址;Data 是该结点保存的数据,为 [−105,105] 区间内的整数;Next 是下一结点的地址。题目保证给出的链表不为空。
Output Specification:
For each case, output in order (from beginning to the end of the list) the resulting linked list. Each node occupies a line, and is printed in the same format as in the input.
对每个测试用例,按链表从头到尾的顺序输出重排后的结果链表,其上每个结点占一行,格式与输入相同。
Sample Input:
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
Sample Output:
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
解题思路
- 初始化并读入链表,并将提前所有链表元素分类;
- 遍历一遍链表,标记其序列号和是否有效的信息;
- 将链表重新排序;
- 按照题目要求输出结果并返回零值。
代码
#include<cstdio>
#include<algorithm>
using namespace std;
#define maxn 100010
struct Node{
int id,next,seq,data,type;
int vivid;
}node[maxn];
int seq=0,st,N,K;
bool cmp(Node a,Node b){
if(a.vivid!=b.vivid){
return a.vivid>b.vivid;
}else if(a.type!=b.type){
return a.type>b.type;
}else{
return a.seq<b.seq;
}
}
void Init(){
int id,data,next;
scanf("%d%d%d",&st,&N,&K);
while(N--){
scanf("%d%d%d",&id,&data,&next);
node[id].id=id;
node[id].data=data;
node[id].next=next;
if(data<0){
node[id].type=3;
}else if(data<=K){
node[id].type=2;
}else{
node[id].type=1;
}
}
}
void Op(){
while(st!=-1){
node[st].seq=seq++;
node[st].vivid=1;
st=node[st].next;
}
sort(node,node+maxn,cmp);
}
void Print(){
int i;
printf("%05d %d ",node[0].id,node[0].data);
for(i=1;i<seq;i++){
printf("%05d\n%05d %d ",node[i].id,node[i].id,node[i].data);
}
printf("-1\n");
}
int main(){
Init();
Op();
Print();
return 0;
}
运行结果