zoukankan      html  css  js  c++  java
  • 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
    ", list[i].address, list[i].data, list[i + 1].address);
    		}
    		else {
    			printf("%05d %d -1", list[i].address, list[i].data);
    		}
    	}
    }
    
  • 相关阅读:
    【CSP-S膜你考】不怕噩梦 (模拟)
    【CSP-S膜你考】 A
    【CSP-S膜你考】即时战略(模拟)
    【CSP-S膜你考】最近公共祖先 (数学)
    【题解】洛谷 P1449 后缀表达式
    【题解】 洛谷 P2649 游戏预言
    【题解】洛谷 P1083 借教室
    【题解】洛谷 P1080 国王游戏
    【题解】洛谷 P1079 Vigenère 密码
    Bzoj4558 [JLoi2016]方
  • 原文地址:https://www.cnblogs.com/custoyth/p/12618240.html
Copyright © 2011-2022 走看看