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 () and an address of the head node, where is the total number of nodes in memory and the address of a node is a 5-digit positive integer. NULL is represented by .
Then 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 [], 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 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<iostream> #include<algorithm> using namespace std; struct Node { int address; int key; int next; bool flag=false;//节点是否在链表上 }nodes[100010]; int N;//节点数量 int head;//首节点 bool cmp(Node a, Node b) { return a.key < b.key; } int main() { int address; cin >> N; cin >> head; for (int i = 0; i < N; i++) { cin >> address; nodes[address].address=address; cin >> nodes[address].key; cin >> nodes[address].next; } int index = head; while (index != -1) { nodes[index].flag = true; index = nodes[index].next; }//从头节点开始访问链表 int list_num = 0;//记录表长 for (int i = 0; i < 100010; i++) { if (nodes[i].flag == false) { nodes[i].key = 9999999;//如果是无效元素,就赋大值,使其排序时到最后 } else list_num++; } sort(nodes, nodes + 100010, cmp); if (list_num == 0) {//表长为0 cout << "0 -1"; } else { //cout << list_num << ' ' << nodes[0].address << endl; printf("%d %05d\n", list_num, nodes[0].address); for (int i = 0; i < list_num - 1; i++) {//更新每个节点的next nodes[i].next = nodes[i + 1].address; } nodes[list_num - 1].next = -1; for (int i = 0; i < list_num - 1; i++) { printf("%05d %d %05d\n", nodes[i].address, nodes[i].key, nodes[i].next); } printf("%05d %d %d\n", nodes[list_num - 1].address, nodes[list_num - 1].key, nodes[list_num - 1].next); } }
最新评论