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 keyand 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
#include 
#include 
#include 
#include 

using namespace std;

#define maxn 100001


struct node
{
	int address, next,data;
	bool flag;
	node()
	{	
		flag = false;
	}
}Node[maxn];

bool cmp(node n1, node n2)
{
	if (n1.flag==false||n2.flag==false)
	{
		return n1.flag > n2.flag;
	}
	else
	{
		return n1.data < n2.data;
	}

    //也可以这样写
	//return n1.flag==false||n2.flag==false?n1.flag>n2.flag:n1.data> n >> first_address;
	for (int i = 0; i < n; i++)
	{
		int a, b, c;
		cin >>a>>b>>c;
		Node[a].address = a;
		Node[a].data = b;
		Node[a].next = c;
	}


	int cnt = 0,i=0;
	//遍历链表找到有效的点  即在链表上的点   将在链表和不在链表的点区别开
	for (i = first_address; i!=-1 ; i=Node[i].next)
	{
		if (Node[i].flag==false)
		{
			Node[i].flag = true;
		}		
		cnt++; //统计有效节点 即在链表上的节点
	}


	
	
	if (cnt==0) //特判  先特判再排序  如果没有节点直接结束啦 就不用排序了 
	{
		cout << "0 -1";
	}
	else
	{
		sort(Node, Node + maxn, cmp); //先排序把在链表上的点 全都弄到最左边 cmp两级排序
		cout << cnt << " ";
		printf("%05d\n", Node[0].address);
		for (int i = 0; i < cnt; i++)
		{
			printf("%05d ", Node[i].address);
			//cout << right << setw(5) << setfill('0') << Node[i].address << " ";
			cout << left << Node[i].data << " ";
			if (i!=cnt-1)
			{
				printf("%05d\n", Node[i + 1].address);  //用cout会“运行超时”  试验过 程序只有printf和cout差别时  cout会超时
				//cout << right << setw(5) << setfill('0') << Node[i+1].address <

 

你可能感兴趣的:(PAT,甲级)