天天看點

PAT A1052 Linked List Sorting

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;
}
           

繼續閱讀