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 [−10510​^{5},10510​^{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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章