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 (< 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

题目要求把链表排序,如果只有一个链表,排序过程中势必会改变连接关系,从而造成循环出错,因此应该至少有两个链表才能进行排序。

这里用另一种方法,把链表放入vector排序,然后输出,这样就可以利用系统的排序函数,需要注意的是题目给出的可能是多个链表,因此应该从头开始向后遍历到-1,处理这个链,而忽略其他部分。

我按照这个思路,最后一个case总是内存超限,比较了网上的代码也没发现自己的问题所在,后来参考了sunbaigui的解法,思路一致,但是他这个代码可以把内存控制在10M以内,代码如下:

#include <iostream>
#include <vector>
#include <algorithm>
#include <stdio.h>

#define MAX 1000000

using namespace std;

typedef struct Node
{
	int me, key, next;
	bool operator < (const Node& n) const
	{
		return key < n.key;
	}
}Node;

int main()
{
	int n, root;
	scanf("%d%d",&n,&root);
	vector<Node> nodeMap(MAX);
	for (int i = 0; i < n; ++i)
	{
		Node node;
		scanf("%d%d%d",&node.me, &node.key, &node.next);
		if(node.me >= 0 && node.me < MAX)
			nodeMap[node.me] = node;
	}

	vector<Node> nodeList;
	int cur = root;
	while(cur >= 0 && cur < MAX)
	{
		nodeList.push_back(nodeMap[cur]);
		cur = nodeMap[cur].next;
	}

    if (nodeList.empty())
	{
		if (root == -1)
			printf("0 -1\n");
		else printf("0 %05d\n",root);
	}
	else
	{
		sort(nodeList.begin(), nodeList.end());
		printf("%d %05d\n", nodeList.size(), nodeList[0].me);
		for (int i = 0; i < nodeList.size(); ++i)
		{
			if(i != nodeList.size()-1)
				printf("%05d %d %05d\n", nodeList[i].me, nodeList[i].key, nodeList[i+1].me);
			else printf("%05d %d -1\n", nodeList[i].me, nodeList[i].key);
		}
	}
	return 0;
}

posted on 2015-07-21 19:44  张大大123  阅读(123)  评论(0编辑  收藏  举报

导航