给定一个单链表,请编写程序将链表元素进行分类排列,使得所有负值元素都排在非负值元素的前面,而 [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
总结:
这道题的实质上和 B1025 链表反转的思想一致,只不过提升了一些,对其节点数据进行相关分类,重新定义临时变量,进行重新存储即可。
代码:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int firstAddr, n, k;
scanf("%d %d %d",&firstAddr, &n, &k);
// 利用数组,对该节点所存储的数据、在一节点地址进行存储
int addrTemp, data[100010] = {0}, nextaddr[100010] = {0};
for(int i=0;i<n;i++) {
scanf("%d",&addrTemp);
scanf("%d %d",&data[addrTemp], &nextaddr[addrTemp]);
}
// 串联链式结构
addrTemp = firstAddr;
vector<int> sequenceList;
while( addrTemp != -1 ) {
sequenceList.push_back(addrTemp);
addrTemp = nextaddr[addrTemp];
}
// 利用数组的形式,对该链表进行分组
vector<int> tempList[3], resultList;
for(int i=0;i<sequenceList.size();i++) {
if( data[ sequenceList[i] ] < 0 )
tempList[0].push_back(sequenceList[i]);
else if( data[ sequenceList[i] ] >= 0 && data[ sequenceList[i] ] <= k )
tempList[1].push_back(sequenceList[i]);
else
tempList[2].push_back(sequenceList[i]);
}
// 用结果链表将该数组重新连接在一起,省去了直接输出的范围判断问题
for(int i=0;i<3;i++) {
for(int j=0;j<tempList[i].size();j++) {
resultList.push_back(tempList[i][j]);
}
}
// 相关格式化输出
int i=0;
for(;i<resultList.size()-1;i++)
printf("%05d %d %05d\n",resultList[i], data[resultList[i]], resultList[i+1] );
printf("%05d %d -1\n",resultList[i], data[resultList[i]]);
return 0;
}