PAT(Advanced) 1074 Reversing Linked List(25 分)

Given a constant K and a singly linked list L, you are supposed to reverse the links of every K elements on L. For example, given L being 1→2→3→4→5→6, if K=3, then you must output 3→2→1→6→5→4; if K=4, you must output 4→3→2→1→5→6.

Input Specification:

Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N (≤10​5​​) which is the total number of nodes, and a positive K (≤N) which is the length of the sublist to be reversed. The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.

Then N lines follow, each describes a node in the format:

Address Data Next

where Address is the position of the node, Data is an integer, and Next is the position of the next node.

Output Specification:

For each case, output the resulting ordered linked list. Each node occupies a line, and is printed in the same format as in the input.

解答:

该题可以用vector来模拟链表的实现,然后每k个一组保存在新的vector变量result中,最后输出结果。刚开始如果过于专注于节点顺序,会把题目搞复杂,要有大局观。 

AC代码如下:

#include<iostream>
#include<vector>
#include<algorithm>

#define maxn 1000000

using namespace std;

typedef struct{
	int data, nxt;
}node;

typedef struct{
	int addr, data;
}node2;
vector<node> vec(maxn);

int main()
{
	int addr, n, k;
	
	cin >> addr >> n >> k;
	for(int i = 0; i < n; ++i)
	{
		int cur, d, nxt;
		scanf("%d %d %d", &cur, &d, &nxt);
		vec[cur].data = d;
		vec[cur].nxt = nxt;
	}
	
	vector<node2> list;
	for(int i = addr; i != -1; i = vec[i].nxt)
	{
		node2 tmp;
		tmp.addr = i; tmp.data = vec[i].data;
		list.push_back(tmp);
	}	
	
	vector<node2> result;
	int i;
	for(i = 0; i + k <= list.size(); i += k)
	{
		int m = i, n = i + k - 1;
		while(n >= m)
		{
			result.push_back(list[n]);
			n--;
		}
	}
	while( i < list.size() )
	{
		result.push_back(list[i++]);
	}
	for(int i = 0; i < result.size(); ++i)
	{
		if(i != result.size() - 1) printf("%05d %d %05d\n", result[i].addr, result[i].data, result[i+1].addr);
		else printf("%05d %d -1\n", result[i].addr, result[i].data);
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37597345/article/details/82316990