问题描述:
A linked list consists of a series of structures, which are not necessarily adjacent in memory. We assume that each structure contains an integer key and a Next pointer to the next structure. Now given a linked list, you are supposed to sort the structures according to their key values in increasing order.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive N (<10^5) and an address of the head node, where N is the total number of nodes in memory and the address of a node is a 5-digit positive integer. NULL is represented by −1.
Then N lines follow, each describes a node in the format:
Address Key Next
where Address is the address of the node in memory, Key is an integer in [−10^5 ,10^5], and Next is the address of the next node. It is guaranteed that all the keys are distinct and there is no cycle in the linked list starting from the head node.
Output Specification:
For each test case, the output format is the same as that of the input, where N is the total number of nodes in the list and all the nodes must be sorted order.
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
需要注意要去除非链表内的结点。
#include<bits/stdc++.h>
using namespace std;
struct link{
int key, next;
}linkl[100005];
struct Link{
int ads, key;
}linklist[100005];
int flag[100005] = {0};
bool cmp(Link a, Link b){
return a.key < b.key;
}
int main(){
int m, first, n;
n = 0;
cin >> m >> first;
for(int i = 0; i < m; i ++){
int tads, tkey, tnext;
scanf("%d %d %d", &tads, &tkey, &tnext);
linkl[tads].key = tkey;
linkl[tads].next = tnext;
}
while(first != -1){
linklist[n].ads = first;
linklist[n].key = linkl[first].key;
first = linkl[first].next;
n ++;
}
if(n == 0){
cout << 0 << " " << -1;
return 0;
}
sort(linklist, linklist + n, cmp);
printf("%d %05d\n", n, linklist[0].ads);
for(int i = 0; i < n; i ++){
printf("%05d %d", linklist[i].ads, linklist[i].key);
if(i == n - 1) cout << " " << -1;
else printf(" %05d\n", linklist[i + 1].ads);
}
return 0;
}