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:

  1. 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:

  1. 5 00001
  2. 11111 100 -1
  3. 00001 0 22222
  4. 33333 100000 11111
  5. 12345 -1 33333
  6. 22222 1000 12345

Sample Output:

  1. 5 12345
  2. 12345 -1 00001
  3. 00001 0 11111
  4. 11111 100 22222
  5. 22222 1000 33333
  6. 33333 100000 -1

思路

本题属于静态链表题型,所以我们可以这样处理:

  1. 把链表写到一个顺序表(数组或向量)里;
  2. sort()函数给顺序表排序;
  3. 打印输出;

这样操作会容易得多。

注意,测试点4会考查dirty data,比如下面输入的结点无法形成链表:

  1. 3 -1
  2. 54322 2 -1
  3. 09876 90 12345
  4. 12345 9 09868

此时应该输出0 -1


代码

测试点1未通过,暂时不明白原因……

  1. #include <iostream> // 21
  2. #include <algorithm>
  3. #include <vector>
  4. using namespace std;
  5. typedef struct node_st {
  6. int addr;
  7. int key;
  8. int next;
  9. }node_st;
  10. node_st myList[100001] = {0x0};
  11. bool comp(int A, int B) {
  12. return myList[A].key < myList[B].key;
  13. }
  14. int main() {
  15. int N(0), START(0);
  16. cin >> N >> START;
  17. // Read list
  18. for(int i = 0; i < N; i++) {
  19. int _addr(0), _key(0), _next(0);
  20. cin >> _addr >> _key >> _next;
  21. myList[_addr].addr = _addr;
  22. myList[_addr].key = _key;
  23. myList[_addr].next = _next;
  24. }
  25. // Copy list to a vector
  26. vector<int> myVec;
  27. for(int i = START; i != -1; i = myList[i].next)
  28. myVec.push_back(i);
  29. if( myVec.size() == 0 ) {
  30. cout << "0 -1\n";
  31. return 0;
  32. }
  33. // Sort by key
  34. sort(myVec.begin(), myVec.end(), comp);
  35. // Dispilay result
  36. cout << myVec.size() << " ";
  37. for(int i = 0; i < N; i++)
  38. printf("%05d\n%05d %d ", myVec[i], myVec[i], myList[ myVec[i] ].key);
  39. cout << -1;
  40. return 0;
  41. }