# PAT 1041 Linked List Sorting (25)（链表排序）

### 题目

1052. Linked List Sorting (25)

400 ms

65536 kB

16000 B

Standard

CHEN, Yue
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:

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

### 解题思路

• 1.先根据头地址保存这个链表所有有效的队列，然后在排序就行了。
• 2.输出的时候要注意保存的链表为空的情况。

### 代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
int nx[99999],va[99999];
struct node{
node(){}
this->v = _v;
}
};
bool cmp(const node &a, const node &b){
return a.v<b.v;
}

int main(int argc, char *argv[])
{
int n,f;
scanf("%d %d",&n,&f);
vector<node> b;
int tem_a,tem_b,tem_c;
for (int i = 0; i < n; ++i) {
scanf("%d %d %d",&tem_a,&tem_b,&tem_c);
nx[tem_a] = tem_c;
va[tem_a] = tem_b;
}
//将有效的链表存好
int now = f;
while (now != -1) {
b.push_back(node(now,va[now]));
now = nx[now];
}
//输出
if (!b.empty()) {
sort(b.begin(),b.end(),cmp);
for (int i = 0; i < b.size()-1; ++i) {
}
}else {
printf("%d %d\n",0,-1);
}
return 0;
}


#### 1028 List Sorting (25)

2018-07-05 20:09:05

#### 1028. List Sorting (25)

2015-06-05 15:52:17

#### PAT (Advanced Level) Practise 1028 List Sorting (25)

2016-03-05 21:11:51

#### 1028. List Sorting (25)【排序】——PAT (Advanced Level) Practise

2015-12-02 20:03:09

#### PAT1052 Linked List Sorting (25)

2014-07-24 01:08:12

#### Pat 1052 Linked List Sorting (25)

2016-04-27 08:48:19

#### 1133. Splitting A Linked List (25)-PAT甲级真题

2017-09-20 09:52:42

#### 1028. List Sorting (25)-PAT甲级真题

2016-08-07 20:12:42