用LUA(和C++)刷PAT (Advanced Level) ——1074 Reversing Linked List

该博客展示了如何使用C++和Lua处理链表数据结构。C++代码通过结构体定义节点,并构建了一个链表,然后按照指定步长进行反转部分链表。Lua部分则使用了栈来实现相同的功能,将链表节点按顺序压栈,达到反转效果。内容涉及到数据结构、链表操作和两种编程语言的实现对比。
摘要由CSDN通过智能技术生成

满分C++:

#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <cmath>
#include <algorithm>

using namespace std;

struct node
{
    int add, next_add;
    int content;
};

int main()
{
    int add, N, K;
    map<int, node> info_map;
    cin>>add>>N>>K;
    for(int i = 0; i < N; i++){
        node n;
        scanf("%d %d %d", &(n.add), &(n.content), &(n.next_add));
        info_map[n.add] = n;
    }
    vector<node> result;
    while(add >= 0){
        result.push_back(info_map[add]);
        add = info_map[add].next_add;
    }
    for(int i = 0; i + K <= result.size(); i += K){
        reverse(&(result[i]), &(result[i + K]));
    }
    for(auto itr = result.begin(); itr != result.end(); itr ++){
        if (itr!= result.begin())
            printf(" %05d\n", itr -> add);
        printf("%05d %d", itr -> add, itr -> content);
    }
    printf(" -1\n");
}

超时lua:

local readFunc = io.read('*a'):gmatch('%p?%w+')

local info_table = {} 

local first_node = readFunc() N = readFunc() K = tonumber(readFunc())

for i = 1, N do
    local node = {add = readFunc(), content = readFunc(), next_node = readFunc()}
    info_table[node.add] = node
end

local stack = {} 
local result_array = {}

while first_node ~= "-1" do
    table.insert(stack, 1, info_table[first_node])
    first_node = info_table[first_node].next_node
    if #stack >= K then
        for _, node in pairs(stack) do
            table.insert(result_array, node)
        end
        stack = {}
    end
end

for index, node in pairs(result_array) do
    print(node.add .. " " .. node.content .. " " .. (result_array[index + 1] and result_array[index + 1].add or (stack[#stack] and stack[#stack].add or "-1")))
end

for index = #stack, 1, -1 do
    node = stack[index]
    print(node.add .. " " .. node.content .. " " .. node.next_node)
end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值