原题干:
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和表头HEAD,接着给出N行数据,每行数据格式为:
节点地址 节点上的数据 节点的下一个地址
要求将链表中的节点进行排序,并输出链表中有几个节点、链表的表头
这道题使用静态链表会很好写,要特别注意这几点:
1、要注意给的节点不一定都是链表上的,判断给的节点是不是链表上的最佳办法是遍历一遍链表,然后给遍历过的节点都做标记。如果第1个测试点过不去,一定是这个问题。
2、要注意链表可能是空表。尽管给了很多节点,但是给定的节点没有一个是链表上的,这个时候的输出为"0 -1"。如果最后一个测试点过不去,一定是这个问题。
代码如下:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
typedef struct {
int addr, data, next;
} node;
bool cmp(node a, node b){
return a.data < b.data;
}
int main(){
int cnt, head;
cin >> cnt >> head;
//读取链表
node L[100000];
for(int i = 0; i < cnt; i++){
int addr;
cin >> addr;
cin >> L[addr].data >> L[addr].next;
L[addr].addr = addr; //读取链表的时候记得保存节点地址
}
//把链表上的节点保存到容器中,其余的点丢弃掉
vector<node> V;
for(; head != -1; head = L[head].next)
V.push_back(L[head]);
//对容器执行排序
sort(V.begin(), V.end(), cmp);
//遍历输出
cout << V.size() << ' ';
for(int i = 0; i < V.size(); i++)
printf("%05d\n%05d %d ", V[i].addr, V[i].addr, V[i].data);
cout << "-1" << endl;
return 0;
}