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 (< 10^5^) 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 [-10^5^, 10^5^], 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
题目大意:给出一些在内存中的节点信息,包括节点坐在位置,该节点保存的值,指向下一个节点的指针; 给出链表头指针,按节点值得大小排序后输出节点
思路: 把节点按照输入信息添加到数组v中, 因为节点位置和其在数组中的下标不一致, 用数组index保存节点在数组v中的位置; 然后根据根节点筛选出在链表中的节点; 对链表中的节点排序, 然后修改节点指针即可
注意点:给出的头结点可能并不存在于给出的信息中, 这是输出的默认头结点应该是-1
1 #include<iostream> 2 #include<vector> 3 #include<algorithm> 4 using namespace std; 5 struct Node{ 6 int addr, val, next; 7 }; 8 9 bool cmp(Node& a, Node& b){return a.val<b.val;} 10 int main(){ 11 int n, root, i; 12 scanf("%d %d", &n, &root); 13 vector<Node> temp(n); 14 vector<int> idx(100000, -1); 15 for(i=0; i<n; i++){ 16 scanf("%d%d%d", &temp[i].addr, &temp[i].val, &temp[i].next); 17 idx[temp[i].addr] = i; //记录几点在数组中的位置 18 } 19 vector<Node> ans; 20 while(root!=-1){//筛选链表中的节点 21 int index = idx[root]; 22 ans.push_back(temp[index]); 23 root = temp[index].next; 24 } 25 //当头结点没有出现的的情况, 则输出应该如下 26 int cnt=ans.size(); 27 if(cnt==0){ 28 printf("0 -1 "); 29 return 0; 30 } 31 sort(ans.begin(), ans.end(), cmp); 32 printf("%d %05d ", cnt, ans[0].addr); 33 for(i=0; i<cnt-1; i++) printf("%05d %d %05d ", ans[i].addr, ans[i].val, ans[i+1].addr); 34 printf("%05d %d %d ", ans[cnt-1].addr, ans[cnt-1].val, -1); 35 return 0; 36 }