PAT甲级1052

1052. Linked List Sorting (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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 (< 105) 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 [-105, 105], 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
using namespace std;
const int MAXN = 100000;
struct Node
{
	int address, data,next;
	Node():address(-1),data(100001),next(-1){}
	bool operator<(Node n)
	{
		return data < n.data;
	}
}node[MAXN];
int main()
{
	int N, start;
	scanf("%d%d", &N, &start);
	vector v; int address;
	for (int i = 0; i < N; i++)
	{
		scanf("%d", &address);
		node[address].address = address;
		scanf("%d %d", &node[address].data, &node[address].next);
	}
	if (node[start].data == 100001||start==-1)//必须判断开始节点地址是不是为NULL,否则最后一个点过不了
	{
		printf("0 -1");//特判,所给节点全无效
		return 0;
	}
	int s = start;
	while (s != -1)
	{
		v.push_back(node[s]);
		s = node[s].next;
		
	}//只存有效节点,也就是从开始位置能够遍历出来的节点,这判断无效节点是个坑,题目一点提示都不给
	sort(v.begin(), v.end());
	start = v[0].address;
	for (int i = 0; i < v.size()-1; i++)
	{
		v[i].next = v[i + 1].address;
	}
	v[v.size()-1].next = -1;
	printf("%d %05d\n", v.size(), start);
	for (int i = 0; i < v.size(); i++)
	{
		if(v[i].next!=-1)
		printf("%05d %d %05d\n", v[i].address, v[i].data, v[i].next);
		else
			printf("%05d %d %d\n", v[i].address, v[i].data, v[i].next);

	}
	return 0;
}

你可能感兴趣的:(PAT)