1052. Linked List Sorting

来源:互联网 发布:陈震媳妇 淘宝店叫什么 编辑:程序博客网 时间:2024/05/21 09:51

1052. Linked List Sorting (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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
考查:单链表相关知识
#include<stdio.h>#include<iostream>#include<vector>#include<algorithm>using namespace std;struct Node{int addr;int data;int next;}buf[1000002];Node v[1000002];bool cmp(Node A, Node B){return A.data < B.data;}int main(){freopen("F://Temp/input.txt", "r", stdin);int n, addr_first, addr_tmp;cin>>n>>addr_first;for(int i = 0; i < n; i ++){cin>>addr_tmp;cin>>buf[addr_tmp].data>>buf[addr_tmp].next;buf[addr_tmp].addr = addr_tmp;}int index = 0;if(addr_first == -1){cout<<"0 -1"<<endl;return 0;}while(buf[addr_first].next != -1){v[index] = buf[addr_first];index ++;addr_first = buf[addr_first].next;}v[index] = buf[addr_first];index ++;sort(v, v+index, cmp);printf("%d %05d\n", index, v[0].addr);for(int i = 0; i < index; i ++){if(index - 1 != i)printf("%05d %d %05d\n", v[i].addr, v[i].data, v[i+1].addr);elseprintf("%05d %d -1\n", v[i].addr, v[i].data);}return 0;}


0 0
原创粉丝点击