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.
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 (≤105) which is the total number of nodes, and a positive K (≤103). The address of a node is a 5-digit nonnegative integer, and NULL is represented by −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 [−105,105], and Next
is the position of the next node. It is guaranteed that the list is not empty.
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
本题主要考察的是静态链表的复杂应用, 选取两个指标作为排序的依据,一个是结点值所在的区间,另一个是结点所在链表上的编号,在这里需要注意的是即便给出的样例中有些结点可能只是形式,不在链表上,因此在排序的过程中,因保证其在链表上在排序,id值的大小可以明确结点是否在链表上
满分代码如下:
#include<bits/stdc++.h>
using namespace std;
const int N=100010;
const int inf=0x3f3f3f3f;
struct Node{
int id;//用来将同一类型按照原链表输出,指定它们在链表中出现的顺序
int address;
int data;
int next;
int flag;//用来记录数字大小的标志
bool operator < (const Node &a)const{
if(flag!=a.flag&&id!=inf&&a.id!=inf){//负数 不大于k的数 大于k的数
return flag<a.flag;
}else{
return id<a.id;
}
}
}node[N];
int first,n,k;
int main(){
//初始化结点在链表中的顺序
for(int i=0;i<N;i++){
node[i].id=inf;
node[i].flag=inf;
}
scanf("%d%d%d",&first,&n,&k);
for(int i=1;i<=n;i++){
int ad;
scanf("%d",&ad);
scanf("%d%d",&node[ad].data,&node[ad].next);
node[ad].address=ad;
if(node[ad].data<0){
node[ad].flag=0;
}else if(node[ad].data<=k){
node[ad].flag=1;
}else{
node[ad].flag=2;
}
}
int p=first,cnt=0;
while(p!=-1){
node[p].id=cnt;
cnt++;
p=node[p].next;
}
sort(node,node+N);
for(int i=0;i<cnt;i++){
if(i==cnt-1){
printf("%05d %d -1\n",node[i].address,node[i].data);
break;
}
printf("%05d %d %05d\n",node[i].address,node[i].data,node[i+1].address);
}
return 0;
}