给定一个单链表,请编写程序将链表元素进行分类排列,使得所有负值元素都排在非负值元素的前面,而 [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 ( ≤ 1 0 5 ≤10^5 ≤105);以及正整数K ( ≤ 1 0 3 ≤10^3 ≤103)。结点的地址是 5 位非负整数,NULL 地址用 − 1 −1 −1 表示。
接下来有 N 行,每行格式为:
Address Data Next
其中 Address
是结点地址;Data
是该结点保存的数据,为
[
1
0
−
5
,
1
0
5
]
[10^{-5},10^5]
[10−5,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
解题思路:
模拟链表模板,分类存储,按类分发
答案代码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 链表节点
const int maxn = 1e6+10;
struct node {
int address, key, next;
}nod[maxn];
int main() {
int head1 = 0, n = 0, k = 0;
cin >> head1 >> n >> k;
// 初始化
int address = 0, key = 0, next = 0;
for (int i = 0; i < n; i++) {
cin >> address >> key >> next;
nod[address].address = address;
nod[address].key = key;
nod[address].next = next;
}
// 装入向量
vector<node> list1;
for (head1; head1 != -1; head1 = nod[head1].next)
list1.push_back(nod[head1]);
// 分类存储
vector<node> v[3];
int sum = list1.size();
for (int i = 0; i < sum; i++) {
if (list1[i].key < 0)
v[0].push_back(list1[i]);
else if (list1[i].key >= 0 && list1[i].key <= k)
v[1].push_back(list1[i]);
else
v[2].push_back(list1[i]);
}
// 按类分发
vector<node> list2;
for (int i = 0; i < 3; i++)
list2.insert(list2.end(), v[i].begin(), v[i].end());
// 更新下标
for (int i = 0; i < sum - 1; i++)
list2[i].next = list2[i+1].address;
list2[sum-1].next = -1;
// 格式化打印
for (int i = 0; i < sum - 1; i++)
printf("%05d %d %05d\n", list2[i].address, list2[i].key, list2[i].next);
printf("%05d %d -1\n", list2[sum-1].address, list2[sum-1].key);
return 0;
}