本题链接:1133 Splitting A Linked List - PAT (Advanced Level) Practice (pintia.cn)
题意:
给定一个链表和数值k,先输出负数,然后输出<=k的数,然后是大于k的
本题采用静态链表存储,注意需要检查链表是否有垃圾结点
代码:
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
struct node {
int now,data, next;
};
const int N = 100010;
node list[N];
//链表不空,但是必须记得判断链表是否连接
//先输出负数,然后输出<k的数,然后是大于k的
int main() {
node xx;
xx.now = 0;
xx.next = 0;
xx.data = 0;
for (int i = 0; i < N; i++) {
list[i] = xx;
}
int head, n, k;
cin >> head >> n >> k;
for (int i = 0; i < n; i++) {
int no, d, ne;
cin >> no;
cin >> list[no].data >> list[no].next;
list[no].now = no;
}
for (int i = 0; i < N; i++) {
if (list[i].next != -1) {
list[i].next = list[list[i].next].now;
}
}
vector<node> res;
int p = head;
while(p !=-1){
if (list[p].data < 0) {
res.push_back(list[p]);
}
p = list[p].next;
}
p = head;
while (p != -1) {
if (list[p].data >= 0 && list[p].data < k) {
res.push_back(list[p]);
}
p = list[p].next;
}
p = head;
while (p != -1) {
if (list[p].data == k) {
res.push_back(list[p]);
}
p = list[p].next;
} p = head;
while (p != -1) {
if (list[p].data > k) {
res.push_back(list[p]);
}
p = list[p].next;
}
for (int i = 0; i < res.size(); i++) {
if (i == res.size() - 1) {
printf("%05d %d -1", res[i].now, res[i].data);
}
else {
printf("%05d %d %05d\n", res[i].now, res[i].data, res[i + 1].now);
}
}
return 0;
}