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 (<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,10​5​​], 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、排序函数解释:

只有当a,b都是在链表中的,才按关键字排序;否则,将出现在链表中的结点放在最前面!!!(所以这里也有一个隐含的优先级在里面)

int cmp(NODE a,NODE b){
	if(a.visit && b.visit)
		return a.key < b.key;
	return a.visit > b.visit;
}

2、input与output中n是不同的:
input中n定义:where N is the total number of nodes in memory
ouput中n定义:where N is the total number of nodes in the list

如果没有考虑到这一点,很可能会导致部分用例通不过。因此要用变量num记录下真正存在于链表中的结点个数,而非内存中的结点个数(因为部分内存中的结点是离散的,不能看做是链表中的结点)。

3、注意考虑n为0的情况!!!否则,部分用例通不过。

代码如下

扫描二维码关注公众号,回复: 9125247 查看本文章
#include<iostream>
#include<algorithm>
using namespace std;
struct NODE{
	int addr;
	int key;
	int next;
	bool visit;
}node[100000];
int cmp(NODE a,NODE b){
	if(a.visit && b.visit)
		return a.key < b.key;
	return a.visit > b.visit;
}
int main()
{
	int n,start,addr,key,next,num=0;
	scanf("%d %d", &n, &start);
	for(int i = 0;  i < n; i++){
		scanf("%d %d %d", &addr,&key,&next);
		node[addr]={addr,key,next,false};
	}
	for(int i = start; i != -1; i = node[i].next){
		node[i].visit = true;
		num++;
	}
	sort(node,node+100000,cmp);
	if(num == 0){
		printf("0 -1");
	}else{
		printf("%d %05d\n", num, node[0].addr);
	}
	for(int i = 0; i < num; i++){
		if(i == num-1){
			printf("%05d %d -1\n", node[i].addr,node[i].key);
		}else{
			printf("%05d %d %05d\n", node[i].addr,node[i].key,node[i+1].addr);
		} 
	}
	return 0;
}
发布了110 篇原创文章 · 获赞 746 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_42437577/article/details/104184016