PAT B# 1025 反转链表

题目链接

https://pintia.cn/problem-sets/994805260223102976/problems/994805296180871168

思路

1.设置结构体,设一个栈

struct node
{
	int address, data, next, order;
};

2.order的初始值为maxn。接着从first开始遍历,每k个node入栈,同时设置order=count++
3.sort按照order由小到大排序,最后遍历i:0~count,输出。

代码

#include <iostream>
#include <algorithm>
#include <stack>
#include <cstdio>
using namespace std;
const int maxn = 100010;//5位的最大下标
struct node
{
	int address, data, next, order;
};
bool cmp(node a, node b) {
	return a.order < b.order;
}
node list[maxn];
int main()
{
	for (int i = 0; i < maxn; i++)
	{
		list[i].order = 2 * maxn;
	}
	int first, n, k,index;
	cin >> first >> n >> k;

	for (int i = 0; i < n; i++)
	{
		cin >> index;
		list[index].address = index;
		cin >> list[index].data >> list[index].next;
	}

	int count = 0;
	stack<node> stk;
	for (int i = first; i != -1 || stk.size() == k;)
	{
		if (stk.size() != k) {
			stk.push(list[i]);
			i = list[i].next;
		}
		else {
			while (!stk.empty()) {
				list[stk.top().address].order = count++;
				stk.pop();
			}
		}
	}
	stack<node> stk_temp;
	while (!stk.empty()) {
		stk_temp.push(stk.top());
		stk.pop();
	}
	while (!stk_temp.empty()) {
		list[stk_temp.top().address].order = count++;
		stk_temp.pop();
	}
	sort(list, list + maxn, cmp);
	
	for (int i = 0; i < count; i++)
	{
		if (i != count - 1) {
			printf("%05d %d %05d\n", list[i].address, list[i].data, list[i + 1].address);
		}
		else {
			printf("%05d %d -1", list[i].address, list[i].data);
		}
	}
}
posted @ 2020-04-02 11:03  cainiao11024  阅读(156)  评论(0编辑  收藏  举报