题目链接:点击打开链接
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 (< 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.
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 12345Sample Output:
5 12345 12345 -1 00001 00001 0 11111 11111 100 22222 22222 1000 33333 33333 100000 -1
我的C++代码:
#include<iostream>
#include<algorithm>
using namespace std;
struct node
{
int address, key, next;
};
bool compare(node a, node b)//自定义排序方法
{
return a.key < b.key;
}
node list1[100000], list2[100000];
int main()
{
int i = 0,index=0;//index是另一个列表的下标
int n, first_address;//n节点个数,first_addresss第一个节点的位置
int temp_address, temp_key, temp_next;
node temp;
scanf("%d %d", &n, &first_address);
for (i = 0; i < n; i++)
{
scanf("%d %d %d", &temp_address, &temp_key, &temp_next);//输入节点地址 键 下一点地址
list1[temp_address].address = temp_address;
list1[temp_address].key = temp_key;
list1[temp_address].next = temp_next;
}
if (first_address == -1)//一个节点都没有
{
printf("0 -1\n");
return 0;//直接退出程序
}
while (first_address != -1)//从头节点位置开始,按顺序将节点串联起来,放进第二个列表
{
list2[index].address = list1[first_address].address;
list2[index].key = list1[first_address].key;
list2[index].next = list1[first_address].next;
first_address = list1[first_address].next;
index++;//第二个列表长度增加1
}
sort(list2, list2 +index , compare);//对第二个列表排序
printf("%d %05d\n", index, list2[0].address);//输出第二个列表节点数,和头节点地址
for (i = 0; i <index-1; i++)
{
printf("%05d %d %05d\n", list2[i].address, list2[i].key, list2[i + 1].address);
//list2[i + 1].address是下一个节点位置
}
printf("%05d %d -1", list2[index- 1].address, list2[index - 1].key);//最后一个节点下一个位置是-1
//system("pause");
return 0;
}