分数 25
全屏浏览题目
切换布局
作者 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 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
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
注意:测试点4,当没有合法数据时输出0 -1
代码如下:
#include<bits/stdc++.h> using namespace std; struct node{ int add; int data; int next; }; bool cmp(node a,node b){ return a.data<b.data; } int main(){ int n,first_add; cin>>n>>first_add; int data[100005],next[100005]; for (int i = 0; i < n; ++i) {//输入 int ad,da,nex; cin>>ad>>da>>nex; data[ad]=da; next[ad]=nex; } node res[n]; int address=first_add,cnt=0; while(address!=-1){//将所有合法的结点放到结构体数组中,并记录合法的结点数量 res[cnt].add=address; res[cnt].data=data[address]; res[cnt].next=next[address]; cnt++; address=next[address]; } if(cnt==0){//没有合法节点则输出0 -1 cout<<"0 -1"<<endl; return 0; } sort(res,res+cnt,cmp);//将cnt个合法节点按值从小到大排序 printf("%d %05d\n",cnt,res[0].add);//输出个数和第一个地址 for (int i = 1; i < cnt ; ++i) {//将每个地址的赋值给上一个地址的next res[i-1].next=res[i].add; if(i==cnt-1)res[i].next=-1;//最后一个结点的next为-1 } for (int i = 0; i < cnt-1; ++i) printf("%05d %d %05d\n",res[i].add,res[i].data,res[i].next); printf("%05d %d -1\n",res[cnt-1].add,res[cnt-1].data);//最后一个结点单独处理,-1不用保留五位 return 0; }