A1052 Linked List Sorting

1.PAT很喜欢考的题型,主要就是用静态链表处理,会很方便,即下标就是地址
2.输入的数据不一定全部都在链表里面,有可能有无用数据
3.得24分的应该是最后一个点,空链表输出0 -1.
4.输出的时候可以取巧,把每行最后一个地址和下一行第一个地址及数据在一起输出,因为这两个address都是data的address

#include <stdio.h>
#include <algorithm>
using namespace std;

const int maxn = 100010;
struct Node{
	int address,data,next;
}node[maxn];	//结构体数组

bool cmp(Node a,Node b)//sort用
{
	return a.data<=b.data;
}
int main(int argc, char const *argv[])
{
	int n,head;
	scanf("%d%d",&n,&head);
	int address,data,next;
	for(int i=0;i<n;i++){
		scanf("%d%d%d",&address,&data,&next);
		node[address].address = address;//下标存地址
		node[address].data = data;
		node[address].next = next;
	}
	Node L[n];	//另外建立数组存储有用数据,排除不在链表上的数据(vector更省空间)
	int len = 0;
	for(int p=head;p!=-1;p=node[p].next){	遍历数据
		L[len++] = node[p];
	}
	sort(L,L+len,cmp);	//按照data大小排序
	printf("%d",len);	//不管链表是否为空,长度一定要输出的
	if(len){			//链表不空
		printf(" %05d\n",len,L[0].address);
		printf("%05d %d",L[0].address,L[0].data);
	}
	for(int i=1;i<len;i++){
		printf(" %05d\n%05d %d",L[i].address,L[i].address,L[i].data);
	}
	printf(" -1");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43108373/article/details/84193332