【PAT】1052 Linked List Sorting 测试点分析

题目

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)N (<10^5)N(<10
5
) 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][−105,105][−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

测试点4考查输出节点全是脏数据的处理结果;(这是老师设置的一个坑点,考虑一定要仔细)
测试数据如下:

输入:
3 -1
54322 2 -1
09876 90 12345
12345 9 09868
输出应该:0 -1

`
AC代码如下:

#include<bits/stdc++.h>
using namespace std;
struct Node{
	int address;
	int data;
	int next;
};
Node link_list[100009],ans[100009];
int cmp(Node a,Node b){
	if(a.data==b.data) return a.address<b.address;
	return a.data<b.data;
}
int main(){
#ifdef ONLINE_JUDGE
#else
	freopen("1.txt","r",stdin);//从1.txt读入 
#endif
	int count,start;
	int a,b,c,num=0;
	cin>>count>>start;
	
	for(int i=0;i<count;i++){
		scanf("%d %d %d",&a,&b,&c);
		link_list[a]={a,b,c};
	}
	if(start==-1){
		cout<<"0 "<<"-1"<<endl;
		return 0;
	}
	for(int i=start;i!=-1;i=link_list[i].next){
		ans[num] = {link_list[i].address,link_list[i].data,link_list[i].next};
		num++;
	}
	sort(ans,ans+num,cmp);
	printf("%d %05d\n",num,ans[0].address);
	for(int i=0;i<num;i++){
		printf("%05d %d ",ans[i].address,ans[i].data);
		if(i!=num-1) printf("%05d\n",ans[i+1].address);
		else cout<<"-1"<<endl;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_39072627/article/details/107009532