【c/c++】PAT A1052 Linked List Sorting

有几组测试数据比较坑,就是某些节点可能无法和题目给的首地址的链表连在一起,是独立、游离的,这也算无效节点,如果所有节点都是有效的话,题目就没必要给出一个head变量!
注意,当没有满足题意的节点时,要输出"0 -1"!
代码如下:

#include<stdio.h>
#include<algorithm>
using namespace std;
const int maxn = 100010;
struct Node{
	int Key;
	int Address;
	int Next;
	bool flag;
}node[maxn];

bool cmp(Node a, Node b){
	if(a.flag == false||b.flag == false){
		return a.flag > b.flag;
	}else{
		return a.Key < b.Key;
	}
}
int main(){
	for(int i=0;i<maxn;i++){
		node[i].flag = false;
	}
	int N, head;
	scanf("%d %d", &N, &head);
	int Address, Key, Next;
	
	for(int i=0;i<N;i++){
		scanf("%d %d %d", &Address, &Key, &Next);
		node[Address].Address = Address;
		node[Address].Key = Key;
		node[Address].Next = Next;
	}
	
	int count = 0;
	while(head!=-1){         //count的作用是为了让一些无效节点被排除掉,从题目给的首地址,可能遇到某些数,他与前面给的数不能连成一个链表!!! 
		node[head].flag = true;
		count++;
		head = node[head].Next;
	}
	
	if(count==0) {       //特判 
		printf("0 -1");
		return 0;
	}
	
	sort(node,node+maxn,cmp);
	for(int i=0;i<count-1;i++){
		node[i].Next = node[i+1].Address;
	}
	node[count-1].Next = -1;
	printf("%d %05d\n", count, node[0].Address);
	for(int i=0;i<count;i++){
		if(node[i].Next!=-1)	printf("%05d %d %05d", node[i].Address, node[i].Key, node[i].Next);   //正确输出-1 
		else	printf("%05d %d -1", node[i].Address, node[i].Key);
		if(i<count-1) printf("\n");
	}
}

AC截图:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值