PAT 甲级 A1052

1022 Digital Library (30分)

题目描述

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.

输入格式

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.

Address Key Next

where Address is the address of the node in memory, Key is an integer in [− 10 5 10​^{5} , 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.

输出格式

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

总结

  1. 题目大概意思是给出一个头结点,让你根据key的值来对链表进行递增排序。既然头结点都给了,那么要注意里面的非有效结点。
  2. 在链表的结点域中设置一个flag,标记是否有效;其次再设置一个标记,判断题目中给的头结点是否有效(否则测试点5过不去)。
  3. 此外注意一下按照5位输出时,-1不要按照5位来输出。

AC代码

#include <iostream>
#include<algorithm>
using namespace std;
struct node {
	int addr, next, key;
	bool flag;
}linkNode[100005];
bool cmp(node a,node b) {
	if (!a.flag || !b.flag) return a.flag > b.flag;  //有效节点在前
	return a.key < b.key;
}
int main()
{
	int n, p, addr, cnt = 0;
	bool flag = false;
	scanf("%d %d", &n, &p);
	for (int i = 0; i < n; i++) {
		scanf("%d", &addr);
		if (addr == p) flag = true;
		linkNode[addr].addr = addr;
		scanf("%d %d", &linkNode[addr].key, &linkNode[addr].next);
	}
	if (!flag) {  //特判
		printf("0 -1\n");
        return 0;
	}
    while (p != -1) {  //计算有效节点个数
        cnt++;
        linkNode[p].flag = true;
        p = linkNode[p].next;
    }
    sort(linkNode, linkNode + 100005, cmp);  //有效节点放左边,且按照key递增排序
    printf("%d %05d\n", cnt, linkNode[0].addr);
    for (int i = 0; i < cnt - 1; i++) {
        printf("%05d %d %05d\n", linkNode[i].addr, linkNode[i].key, linkNode[i+1].addr);
    }
    printf("%05d %d -1\n", linkNode[cnt-1].addr, linkNode[cnt-1].key);  //打印最后一个节点
	return 0;
}
发布了16 篇原创文章 · 获赞 0 · 访问量 357

猜你喜欢

转载自blog.csdn.net/qq_38507937/article/details/104315880
今日推荐