PAT 甲级 1052 Linked List Sorting (纳尼?最后一个case段错误???)

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

算法分析
1、静态链表,首先将存在于list中的结点全部筛选出来,放入vector容器中。
2、引入了散列的思想,用空间换时间,index就是当前adr,因为输出的时候要输出当前adr,因此,需要在结点中也记录当前adr。
3、最后一个case段错误。
划重点
段错误的原因:最常见的就是数组越界,栈溢出
此时需要检查数组的index是否会出现非法值,本题中的 -1
将定义的规模很大的容器从main函数中移到全局变量中
PAT 甲级 1052 Linked List Sorting (纳尼?最后一个case段错误???)_第1张图片

以下是AC代码

#include 
#include 
#include 
using namespace std;
struct Node{
	int key;
	int next;
	bool flag;//是否在链表中 
	int adr;
}node[100001];
vector<Node> v;
bool cmp(Node a,Node b)
{
	return a.key<b.key;
}
int main()
{
	int n,adr;
	int a,b,c;
	cin>>n>>adr;
	//添加后成功解决最后一个用例段错误 
	if(adr==-1)
	{
		printf("0 -1\n");
		return 0;
	}
	for(int i=0;i<n;i++)
	{
		node[i].flag=false; //初始化 
	}	
	for(int i=0;i<n;i++)
	{	
		scanf("%d %d %d",&a,&b,&c);
		node[a].key=b;
		node[a].next=c;
		node[a].adr=a;	
	}
	while(adr!=-1)
	{
		v.push_back(node[adr]);
		adr=node[adr].next;
	}
	sort(v.begin(),v.end(),cmp); //只把在链表中的结点进行排序 
	int size=v.size();
	printf("%d %05d\n",size,v[0].adr);
	vector<Node>::iterator it;
	for(it=v.begin();it!=v.end()-1;it++)
	{	
		printf("%05d %d %05d\n",it->adr,it->key,(it+1)->adr);
	}
	printf("%05d %d -1\n",it->adr,it->key);	//输出最后一个结点	
	return 0;
}

你可能感兴趣的:(PAT)