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.
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.
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
思路:很典型的一道PAT链表题了,具体的结构实现就是用一个结构体里面存储key和next,然后他的结构体数组下标代表的就是目前这个数的地址,要注意的就是是否有多余的链表,从head开始一直next,直到最后一个,这样就把有效的链表都统计了下来,因为题目明确说明了key值是独一无二的(distinct),所以我们就用map来存储对应的key值,然后对应到地址上面,map的自动排序功能就可以让我们顺利输出啦!
代码:
#include <bits/stdc++.h>
using namespace std;
struct link{
int val;
int next;
};
int main(){
int n,head;
scanf("%d%d",&n,&head);
int i;
link a[100000];
for(i=0;i<n;i++){
int ad,ky,nxt;
scanf("%d%d%d",&ad,&ky,&nxt);
a[ad].val=ky;
a[ad].next=nxt;
}
map<int,int>mp;
map<int,int>::iterator it;
while(head!=-1){//统计有效链表的值
mp[a[head].val]=head;
head=a[head].next;
}
it=mp.begin();
if(mp.size()==0){//对0的情况特殊分析
printf("0 -1");
return 0;
}
printf("%d %05d\n",mp.size(),it->second);
for(;it!=mp.end();it++){
if(it==mp.begin())printf("%05d %d ",it->second,it->first);
else printf("%05d\n%05d %d ",it->second,it->second,it->first);
}
printf("-1");
}
?
|