a1052 Linked List Sorting

本文详细介绍了一种使用C++实现静态链表的方法,通过结构体(struct)来存储链表节点,包括地址、键值和下一个节点的指针。文章提供了一个完整的代码示例,展示了如何读取输入并构建链表,以及如何对链表进行排序和遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现在是2018年8月16日20:25:09,洛杉矶时间为8.16日5:25,唱晚还没起床吧,我好想你。 


静态链表,只用struct结构就可以实现目的; 

#include<cstdio>
#include<algorithm>
using namespace std;

struct acw {
	int address,key,next;
	bool flag;
}cw[100010];

bool cmp(acw a , acw b){
	if (a.flag == false || b.flag == false) return a.flag > b.flag;
	else return a.key < b.key;
}
int main()
{
	int n,i,begin,address,count=0;
	scanf("%d%d", &n,&begin);
	for (i = 0; i < n; i++)
	{
		scanf("%d", &address);
		scanf("%d%d",&cw[address].key, &cw[address].next);
		cw[address].address = address;
	}
	//初始化
	for (i = 0; i < 100010; i++)
	{
		cw[i].flag = false;
	}
	for (int p = begin; p != -1; p = cw[p].next)
	{
		cw[p].flag = true;
		count++;
	}
	if (count != 0)
	{
		sort(cw, cw + 100010, cmp);
		printf("%d %05d\n", count, cw[0].address);
		for (i = 0; i < count - 1; i++)
		{
			printf("%05d %d %05d\n", cw[i].address, cw[i].key, cw[i+1].address);
		}
		printf("%d %d -1", cw[i].address, cw[i].key);
	}
	else printf("0 -1");

	return 0;
}

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值