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);
    		}
    	}
    }
    
  • 相关阅读:
    VS Code 隐藏 .meta 文件
    CentOS7安装之后无法上网
    windows通过ssh方式访问CentOS7
    解决libc.so.6: version `GLIBC_2.18' not found问题
    Node.js ArrayBuffer 转为字符串
    centos7 tar, zip 解压文件命令(tar, zip)
    CentOS7安装 clang
    CentOS7开启 ssh 22端口
    MongoDB手册
    C++回调函数
  • 原文地址:https://www.cnblogs.com/custoyth/p/12618240.html
Copyright © 2011-2022 走看看