PAT A1052 Linked List Sorting

版权声明:原创文章,转载请注明出处 https://blog.csdn.net/hza419763578/article/details/88538295

1052 Linked List Sorting (25 分)

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

本题易错点,难点在与可能存在某些结点根本连不上链表,不在连好的链表上,题目只说没有重复的key,没有环,但并没有说不会有多余的结点

#include<iostream>
#include<algorithm>
#include <cstdio>
using namespace std;
const int N=1e5+10;
struct Node
{
	int address;
	int key;
	int next;
	bool flag;

	Node(){flag=false;}
	
}node[N];

bool cmp(Node n1,Node n2){
	if(n1.flag==false||n2.flag==false){//有一个是空闲结点时直接放在最右边
		return n1.flag>n2.flag;//true=1 false=0  true在前面
	}else{
		return n1.key<n2.key;
	}
}

int main(){
	int n,head;
	cin>>n>>head;
	int address,key,next;
	for(int i=0;i<n;i++){
		cin>>address>>key>>next;
		node[address].address=address;
		node[address].key=key;
		node[address].next=next;
	}

	int count=0;
	for(int p=head;p!=-1;p=node[p].next){
		node[p].flag=true;
		count++;
	}
	if(count==0){
		printf("0 -1\n");
	}else{
		sort(node,node+N,cmp);//排序的复杂度高  但是将不在链表中的都筛选出去了
		//链表长度可能变了 count不再是n
		printf("%d %05d\n",count,node[0].address);
		int i;
		for(i=0;i<count-1;i++){//已经知道有count个了  排序后肯定在最前面
			printf("%05d %d %05d\n",node[i].address,node[i].key,node[i+1].address );
		}
		printf("%05d %d %d\n",node[i].address,node[i].key,-1);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/hza419763578/article/details/88538295