Linked List Sorting
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 (< 105) 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 [-105, 105], 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
题意
给定n个结点的地址、数据、下个结点地址,要求将该链表上的结点按数据从小到大进行输出。
思路
使用静态链表进行处理,由于所给结点可能并不在链表上,所以在定义结点时追加一个成员变量flag用以判断是否为有效结点(有效则flag = 1,无效则flag = 0)。读取数据后,遍历链表,并对有效结点进行标记。利用sort对结点进行排序,比较函数满足下列规则:如果两结点中存在无效结点,则按flag值从大到小排序,这样可以把有效结点全部集中到数组的最前面;如果两结点都是有效结点,则按数据值从小到大排序。
代码实现
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 100000;
struct Node
{
int add, key, next;
int flag;
Node(): flag(0) {} // 构造函数,初始化flag为0
} node[maxn];
bool cmp(Node a, Node b)
{
if (!a.flag || !b.flag) // 存在无效结点,按flag从大到小排列
return a.flag > b.flag;
else // 全是有效结点,按key值从小到大排列
return a.key < b.key;
}
int mark(int p) // 标记有效结点,并统计其总个数
{
int count = 0;
while (p != -1)
{
node[p].flag = 1;
count++;
p = node[p].next;
}
return count;
}
int main()
{
int n, start;
int ad;
int count; // 记录有效结点个数
scanf("%d %d", &n, &start);
for (int i = 0; i < n; i++)
{
scanf("%d", &ad);
node[ad].add = ad;
scanf("%d %d", &node[ad].key, &node[ad].next);
}
count = mark(start);
if (count == 0) // 注意存在没有有效结点的情况
printf("0 -1");
else
{
sort(node, node + maxn, cmp);
printf("%d %05d\n", count, node[0].add);
for (int i = 0; i < count; i++) // 对最后一个结点及其他结点应该分情况处理
if (i != count - 1)
printf("%05d %d %05d\n", node[i].add, node[i].key, node[i + 1].add);
else
printf("%05d %d -1", node[i].add, node[i].key);
}
return 0;
}