1074 Reversing Linked List 25

cpp 复制代码
#include <cstdio>
const int maxn = 100010;
struct Node{
    int address, data, next;
}nodes[maxn];

int main() {
    int head,n,k;
    scanf("%d%d%d", &head, &n, &k);
    int add;
    for(int i = 0; i < n; i++){
        scanf("%d", &add);
        scanf("%d%d", &nodes[add].data, &nodes[add].next);
        nodes[add].address = add;
    }
    //有效节点数目
    int v = head;
    int num = 1;
    while(nodes[v].next != -1){
        num++;
        v = nodes[v].next;
    }

    
    int heads[maxn];
    int tails[maxn];
    
    int next;
    int pre = head;
    int cur = nodes[head].next;
    int curHead = head;
    int times = num / k;
    for(int i = 0; i < times; i++){
        tails[i] = curHead;
        int s = 1;
        while(s < k){
            next = nodes[cur].next;
            nodes[cur].next = pre;
            pre = cur;
            cur = next;
            s++;
        }
        heads[i] = pre;
        curHead = cur;
        pre = cur;
        cur = nodes[cur].next;
    }
    nodes[tails[times-1]].next = curHead;
    for(int i = 0; i < times-1; i++){
        nodes[tails[i]].next = nodes[heads[i+1]].address;
    }
    int ans = heads[0];
    while(nodes[ans].next != -1){
        printf("%05d %d %05d\n", nodes[ans].address, nodes[ans].data, nodes[ans].next);
        ans = nodes[ans].next;
    }
    printf("%05d %d -1\n", nodes[ans].address, nodes[ans].data);
    return 0;
}
相关推荐
菜鸟5555538 分钟前
图论:Floyd算法
算法·图论
KyollBM41 分钟前
【Luogu】每日一题——Day21. P3556 [POI 2013] MOR-Tales of seafaring (图论)
图论
呼啦啦啦啦啦啦啦啦5 小时前
常见的排序算法
java·算法·排序算法
胡萝卜3.06 小时前
数据结构初阶:排序算法(一)插入排序、选择排序
数据结构·笔记·学习·算法·排序算法·学习方法
地平线开发者6 小时前
LLM 中 token 简介与 bert 实操解读
算法·自动驾驶
lyx33136967596 小时前
Pandas数据结构详解Series与DataFrame
数据结构·pandas
scx201310047 小时前
20250814 最小生成树和重构树总结
c++·算法·最小生成树·重构树
阿巴~阿巴~7 小时前
冒泡排序算法
c语言·开发语言·算法·排序算法
散1127 小时前
01数据结构-交换排序
数据结构·算法
yzx9910138 小时前
Yolov模型的演变
人工智能·算法·yolo