其他分享
首页 > 其他分享> > 【附段错误原因,最后两个测试点】1052 Linked List Sorting (25 分)【链表类题目总结】

【附段错误原因,最后两个测试点】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;	
}

耗时:

在这里插入图片描述


求赞哦~ (✪ω✪)

标签:node,25,测试点,int,value,链表,05d,fir
来源: https://blog.csdn.net/weixin_43899069/article/details/114005264