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);
    		}
    	}
    }
    
  • 相关阅读:
    场景设计法
    判定表驱动分析方法
    错误推测法
    Ubuntu软件包管理命令全面集锦
    MySql模糊查询
    VC++ 列表控件的使用方法
    Java笔记原生数据类型【二】
    DEDECMS 关键字不能小于2个字节!
    Linux 使用yum install安装mysql登陆不上解决办法
    PHP数据学习-二维数组【3】
  • 原文地址:https://www.cnblogs.com/custoyth/p/12618240.html
Copyright © 2011-2022 走看看