目录
1,题目描述
Sample Input:
5 00001
11111 100 -1
00001 0 22222
33333 100000 11111
12345 -1 33333
22222 1000 12345
Sample Output:
5 12345
12345 -1 00001
00001 0 11111
11111 100 22222
22222 1000 33333
33333 100000 -1
题目大意
链表排序,但要注意,题目给出的节点中,并不是所有节点都在链上,所以需要先遍历哪些是在链上的。
输入
- 第一行:节点个数N,头节点地址;
- 其余N行:N个节点的地址,存放的内容,下一个节点的地址;
输出
- 排序后,输出规格同上;
2,思路
注意点
- 并不是所有节点都在以head为头节点的链表上(测试点1);
- 头节点可能为空,即head=-1(测试点4);
- all the keys are distinct:所有节点的值唯一;
- there is no cycle in the linked list starting from the head node:以该头节点为首的链表不存在循环;
数据结构
- struct node{int add, key, next; bool flag;} lis[100001]:设计节点,flag为记录该节点是否在链表上;
算法
- 声明结构体数组struct node{。。。} lis[100001],下标代表地址(便于模拟链表的执行过程) ;
- 根据头节点,寻找以该头节点为首的链表上的所有节点,将这些节点做上标记flag=true,并记录此链表上的节点数目num;
- 将结构体数组进行排序:在设计cmp函数时,注意将flag=false的节点放在最后;
- 按序输出结构体数组lis中下标为0 - num-1的节点;
3,心路历程
第一搏:
(一开始不明白为什么要给出头节点。。。)
然后查了一下大神的做法,,,并不是所有节点都在链表上(测试点1),头节点是为了给出一条链。
第二搏:
提前遍历一遍链表,将在链上的节点标记出来,排序后只输出标记后的节点。
万恶的测试点4.。。。
第三搏:
其实仔细想想也容易理解,头节点也可能为空,所以就有了下面的测试数据:
5 -1
11111 100 -1
00001 0 22222
33333 100000 11111
12345 -1 33333
22222 1000 12345
最后一击!
4,代码
#include<iostream>
#include<vector>
#include<string.h>
#include<algorithm>
using namespace std;
struct node{
int add, key, next;
bool flag; //flag判断是否在链上 测试点1
}lis[100001];
bool cmp1(node a, node b){
if(a.flag == true && b.flag == true){
return a.key < b.key;
}else if(a.flag == true && b.flag == false){
return true;
}else
return false;
}
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif
int N, head;
scanf("%d %d", &N, &head);
int add, k, n;
for(int i = 0; i < N; i++){
scanf("%d %d %d", &add, &k, &n);
lis[add] = {add, k, n, false}; //lis为结构体数组
}
add = head;
int num = 0;
while(add != -1){
lis[add].flag = true;
add = lis[add].next;
num++;
}
sort(lis, lis + 100000, cmp1);
if(num == 0){ //测试点4
printf("0 -1");
return 0;
}
int i;
printf("%d %05d\n", num, lis[0].add);
for(i = 0; i < num -1; i++){
printf("%05d %d %05d\n", lis[i].add, lis[i].key, lis[i+1].add);
}
printf("%05d %d %d\n", lis[i].add, lis[i].key, -1);
return 0;
}