PAT A1052 Linked List Sorting (25分)

在这里插入图片描述

#include <cstdio>
#include <algorithm>

using namespace std;

struct Node{
    
    
	int address;
	int data;
	int next;
	int flag;
	Node(){
    
    
		flag = 0;
	}
}node[100010];

bool cmp(Node n1, Node n2){
    
    
	if(!(n1.flag==1 && n2.flag==1)){
    
    
		return n1.flag > n2.flag;
	}else{
    
    
		return n1.data < n2.data;
	}
}

int main(){
    
    
	int n, h;
	scanf("%d %d", &n, &h);
	
	int ad, da, ne;
	for(int i=0; i<n; i++){
    
    
		scanf("%d %d %d", &ad, &da, &ne);
		node[ad].address = ad;
		node[ad].data = da;
		node[ad].next = ne;
	}
	
	int count = 0;
	while(h != -1){
    
    
		count++;
		node[h].flag = 1;
		h = node[h].next;
	}
	
	if(count == 0){
    
    
		printf("0 -1");
		return 0;
	}
	
	sort(node, node+100010, cmp);
	
	printf("%d %05d\n", count, node[0].address);
	int i = 0;
	while(node[i].flag != 0){
    
    
		if(node[i+1].flag != 0){
    
    
			printf("%05d %d %05d\n", node[i].address, node[i].data, node[i+1].address);
		}else{
    
    
			printf("%05d %d -1\n", node[i].address, node[i].data);			
		}
		i++;
	}
	
	return 0;
} 

此题思路不难想,但是要注意有点测试点的数据可能会给不存在链表上的,因此需要先遍历一次链表并将链表上有的结点标记好。
还有一处要注意的是如果给出的数据都是无效的,即链表为空,需要特判输出“0 -1”。

猜你喜欢

转载自blog.csdn.net/weixin_45964844/article/details/113090889