一、题目描述
原题链接
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:
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
二、解题思路
一道比较简单的链表题,我们可以通过静态链表实现,将每个节点建立为结构体,包括地址、数据和下一个元素的地址。用while循环遍历一遍链表,将节点存入vector<Node> list中,随后用sort函数进行排序,随后进行输出即可。
三、AC代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 100010;
struct Node
{
int add, key, next;
}node[maxn];
vector<Node> list;
bool cmp(Node a, Node b)
{
return a.key < b.key;}
int main()
{
int N, first, tmp;
scanf("%d%d", &N, &first);
for(int i=0; i<N; i++)
{
scanf("%d", &tmp);
scanf("%d%d", &node[tmp].key, &node[tmp].next);
node[tmp].add = tmp;
}
tmp = first;
while(tmp != -1)
{
list.push_back(node[tmp]);
tmp = node[tmp].next;
}
sort(list.begin(), list.end(), cmp);
int sze = list.size();
if(sze == 0)
{
printf("0 -1");
return 0;
}
printf("%d %05d\n", sze, list[0].add);
for(int i=0; i<sze-1; i++)
{
printf("%05d %d %05d\n", list[i].add, list[i].key, list[i+1].add);
}
printf("%05d %d -1", list[sze-1].add, list[sze-1].key);
return 0;
}