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 (<10e5) 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 [−10e5,10e5], 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
题目大意:给出一个静态链表,要求将链表排序,再按照key值从小到大顺序输出所有节点。
分析:注意输入的节点不一定挂在当前的链表上,当节点数为0时输出0 -1.
建立结构体数组,按照从首地址开始的顺序(直到-1)遍历一遍整个链表,将在链表中的结点的flag标记为true,统计有效结点的个数cnt并把这些节点另外存储到新的数组中。 然后将链表进行排序输出即可。
cpp
#include<algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <ctime>
#include <cmath>
using namespace std;
typedef struct node
{
int add,key,next,flag;
}node;
node temp[100010],ans[100010];
bool cmp(node a,node b)
{
return a.key<b.key;
}
int main(void)
{
#ifdef test
freopen("in.txt","r",stdin);
//freopen("in.txt","w",stdout);
clock_t start=clock();
#endif //test
int n,first;scanf("%d%d",&n,&first);
int cnt=0;
for(int i=0;i<n;++i)
{
int a,b,c;scanf("%d%d%d",&a,&b,&c);
temp[a].add=a,temp[a].key=b,temp[a].next=c,temp[a].flag=1;
}
int index=first;
if(temp[index].flag==1)
{
while(temp[index].next!=-1)
{
ans[cnt++]=temp[index];
index=temp[index].next;
}
ans[cnt++]=temp[index];
sort(ans,ans+cnt,cmp);
printf("%d ",cnt);
if(ans[0].add!=-1)printf("%05d\n",ans[0].add);
else printf("-1\n");
for(int i=0;i<cnt;++i)
{
printf("%05d %d ",ans[i].add,ans[i].key);
if(i+1!=cnt)printf("%05d\n",ans[i+1].add);
else printf("-1\n");
}
}
else printf("0 -1\n");
#ifdef test
clockid_t end=clock();
double endtime=(double)(end-start)/CLOCKS_PER_SEC;
printf("\n\n\n\n\n");
cout<<"Total time:"<<endtime<<"s"<<endl; //s为单位
cout<<"Total time:"<<endtime*1000<<"ms"<<endl; //ms为单位
#endif //test
return 0;
}