浙江大学PAT_甲级_1052. Linked List Sorting (25)

来源:互联网 发布:中国m2历年数据曲线图 编辑:程序博客网 时间:2024/06/05 00:35

题目链接:点击打开链接

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 0000111111 100 -100001 0 2222233333 100000 1111112345 -1 3333322222 1000 12345
Sample Output:
5 1234512345 -1 0000100001 0 1111111111 100 2222222222 1000 3333333333 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;}


1 0
原创粉丝点击