1052 Linked List Sorting (25 分) 链表排序

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 [−10​5​​,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

题意:先输入链表的结点数目和链表的头结点的地址,再输入链表中每个结点的地址和这个结点对应的值和下一个结点的地址,再按照每个结点的值的大小从小到大再给链表进行排序。
思路:pat中关于链表的定义一般都是定义一个结构体,结构体中有链表的当前地址,链表当前地址结点对应的值,链表下一个结点的地址,然后再弄一个flag便于下面来探测有没有访问过这个点,判断是不是孤立结点。再写好cmp函数,先比较结点的flag,flag为true的情况下肯定是优先于为false的情况,然后再按照值的大小从小到大排序。从给定的头结点开始记录在链上的结点的个数几位cnt,便利完成后,先判断cnt是不是为0,如果为0的话就输出0,-1,这个如果不写的话,最后一个测试点过不去。接下来排好序,直接把链表输出即可。

#include<iostream>
#include<cstdio>
#include<stack> 
#include<queue>
#include<vector>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<set>
#include<map>

using namespace std;

struct node {
	int address;
	int key;
	int next;
	bool flag;
} a[100010]; 

bool cmp(node a,node b) {
	return !a.flag || !b.flag ? a.flag > b.flag : a.key < b.key;
}

int main() {
	int n,address1;
	scanf("%d%d",&n,&address1);
	int d,e,f;
	for(int i = 0;i < n;i++) {
		scanf("%d%d%d",&d,&e,&f);
		a[d].address = d;
		a[d].key = e;
		a[d].next = f;
		a[d].flag = false;
	}
	int cnt = 0;
	for(int i = address1;i != -1;i = a[i].next) {
		a[i].flag = true;
		cnt++;
	}
	//最后一个测试点测试cnt为0的情况 
	if(cnt == 0) {
		printf("0 -1\n");
	} else {
		sort(a,a + 100000,cmp);
		printf("%d %05d\n",cnt,a[0].address);
		for(int i = 0;i < cnt;i++) {
			printf("%05d %d ",a[i].address,a[i].key);
			if(i != cnt - 1) {
				printf("%05d\n",a[i + 1].address);
			} else {
				printf("-1\n");
			}
		}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值