【附段错误原因,最后两个测试点】1052 Linked List Sorting (25 分)【链表类题目总结】
立志用最少的代碼做最高效的表達
PAT甲級最優題解——>傳送門
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
題意:給定一些節點,要求將鏈表按值升序排序并輸出。
鏈表類型題總結(適用所有鏈表題):
1. 一定要將鏈表構造出來再進行操作,因為樣例中有很多無效節點。
2. 考慮頭結點為-1的情況
3. 輸出單一頭結點時注意頭結點的也要使用%05d
#include<bits/stdc++.h> using namespace std; struct lnode{int value = 0, next = -1; }node[100010];bool cmp(int x1, int x2) {return node[x1].value < node[x2].value; }int main() {int n, fir; scanf("%d%d", &n, &fir);//頭結點為-1的特殊情況 if(fir == -1) { printf("0 -1\n"); return 0; }//構建鏈表。這一步的目的是去除無效節點。 for(int i = 0; i < n; i++) {int x; cin >> x;cin >> node[x].value >> node[x].next;}//遍歷鏈表,將鏈表中的節點壓入vector。 //注意這里只存儲地址即可。因為可以通過地址找到value vector<int>v;while(fir != -1) {v.push_back(fir); //只存儲地址即可。fir = node[fir].next;}sort(v.begin(), v.end(), cmp);int len = v.size();//注意這里頭結點的輸出也要用%05d,別忘了 printf("%d %05d\n", len, v[0]);for(int i = 0; i < len-1; i++) printf("%05d %d %05d\n", v[i], node[v[i]].value, v[i+1]);printf("%05d %d -1\n", v[len-1], node[v[len-1]].value);return 0; }
耗時:
求贊哦~ (?ω?)
總結
以上是生活随笔為你收集整理的【附段错误原因,最后两个测试点】1052 Linked List Sorting (25 分)【链表类题目总结】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【详细注释】1051 Pop Seque
- 下一篇: 1054 The Dominant Co