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.
Each input file contains one test case. For each case, the first line contains a positive N (<105) 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 [−105 ,105 ], 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.
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.
5 00001
11111 100 -1
00001 0 22222
33333 100000 11111
12345 -1 33333
22222 1000 12345
5 12345
12345 -1 00001
00001 0 11111
11111 100 22222
22222 1000 33333
33333 100000 -1
这题和【1074 Reversing Linked List (25分)】很像,不过1074是让你反转链表,而本题是让你对链表的data域从小到大进行排序。做法还是一样的,先把题目给的数据全部读入到Node数组里,然后再从头结点开始走,把有效结点依次放到List数组里,再用cmp函数按data的值从小到大给List数组排个序,此时,我们的List数组的address和data都已经满足题目要求了,因此,只要从后往前改List数组每个元素的next域即可(前一个的next域是后一个的address)。
这题和1074不同的地方在于,这题可能出现全是无效结点的情况,所以此时要特判输出“0 -1”。
于是我得出了一个结论:
如果这类链表的题目有那么一两个测试点WA,多半以下两种情况:
#include
#include
#include
#include
#include
using namespace std;
const int maxn = 100001;
struct node{
int address;
int data;
int next;
}Node[maxn], List[maxn];
bool cmp(node a, node b){
return a.data<b.data;
}
int main(){
int N, headAddress;
scanf("%d%d", &N, &headAddress);
for(int i=0;i<N;i++){
int tmpAddress, tmpData, tmpNext;
scanf("%d%d%d", &tmpAddress, &tmpData, &tmpNext);
Node[tmpAddress].address = tmpAddress;
Node[tmpAddress].data = tmpData;
Node[tmpAddress].next = tmpNext;
}
int nowAddress = headAddress;
int nextAddress = Node[headAddress].next;
int index = 0;
while(nowAddress!=-1){
List[index].address = nowAddress;
List[index].data = Node[nowAddress].data;
List[index].next = nextAddress;
index++;
nowAddress = nextAddress;
nextAddress = Node[nextAddress].next;
}
if(index==0) printf("0 -1");
else{
sort(List, List+index, cmp);
List[index-1].next = -1;
if(index-2>=0){
for(int i=index-2;i>=0;i--){
List[i].next = List[i+1].address;
}
}
printf("%d %05d\n", index, List[0].address);
for(int i=0;i<index;i++){
if(List[i].next==-1) printf("%05d %d %d\n", List[i].address, List[i].data, List[i].next);
else printf("%05d %d %05d\n", List[i].address, List[i].data, List[i].next);
}
}
return 0;
}