PAT A1052 Linked List Sorting

PAT A1052 Linked List Sorting

在这里插入图片描述

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:
    同1032,在静态链表中设置标记位,并先后以标记位(筛选出有效节点),data(使有效节点排序)排序

  • code1:

#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 100010;

struct Node{
	int address, data, 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.data < b.data;
}

int main(){
//	//初始化:
	for(int i = 0; i < maxn; ++i)
		node[i].flag = false; 
	int n, s, pos;
	scanf("%d%d", &n, &s);
//	int pos, data, next;
	for(int i = 0; i < n; ++i){
//		scanf("%d%d%d", &pos, &data, &next);
//		node[pos].address = pos;
//		node[pos].data = data;
//		node[pos].next = next;
		scanf("%d", &pos);
		scanf("%d%d", &node[pos].data, &node[pos].next);
		node[pos].address = pos;
	}
	int count = 0;
	while(s != -1){
		count++;
		node[s].flag = true;
		s = node[s].next;
	}
//	printf("%d", count);
	if(count == 0)
	//特殊情况:没有有效节点,链表位空 
		printf("0 -1");
	else{
		sort(node, node+maxn, cmp);
		for(int i = 1; i <= count; ++i){
			node[i-1].next = node[i].address;
		}
		node[count-1].next = -1;
		printf("%d %05d\n", count, node[0].address);
		//注意!!:输出第一行的5是指有效节点数即count,而不是总节点数n 
		for(int i = 0; i < count-1; ++i){
			printf("%05d %d %05d\n", node[i].address, node[i].data,
					node[i].next);
		}
		printf("%05d %d -1", node[count-1].address, node[count-1].data);
	}
	return 0;
}
  • 思路:链表模板 + 下标排序
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
struct Node{
	int data, next;
}node[maxn];

void Print(vector<int> v){
	int last = v.size() - 1;
	if(last < 0) printf("0 -1");	//Wrong 1:样例4 
	else{
		printf("%d %05d\n", v.size(), v[0]);
		for(int i = 0; i < v.size()-1; ++i){
			printf("%05d %d %05d\n", v[i], node[v[i]].data, v[i+1]);
		}
		printf("%05d %d -1", v[last], node[v[last]].data);
	}
}
bool cmp(int a, int b){
	return node[a].data < node[b].data;
}
int main(){
	int n, head;
	scanf("%d %d", &n, &head);
	for(int i = 0; i < n; ++i){
		int t_add;
		scanf("%d", &t_add);
		scanf("%d %d", &node[t_add].data, &node[t_add].next);		
	}
	vector<int> ans;
	while(head != -1){
		ans.push_back(head);
		head = node[head].next;
	}
	sort(ans.begin(), ans.end(), cmp);
	Print(ans);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值