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;
}
相关推荐
芜湖xin18 分钟前
【题解-洛谷】P1706 全排列问题
算法·dfs
chao_7891 小时前
链表题解——两两交换链表中的节点【LeetCode】
数据结构·python·leetcode·链表
曦月逸霜2 小时前
第34次CCF-CSP认证真题解析(目标300分做法)
数据结构·c++·算法
海的诗篇_3 小时前
移除元素-JavaScript【算法学习day.04】
javascript·学习·算法
自动驾驶小卡3 小时前
A*算法实现原理以及实现步骤(C++)
算法
Unpredictable2223 小时前
【VINS-Mono算法深度解析:边缘化策略、初始化与关键技术】
c++·笔记·算法·ubuntu·计算机视觉
编程绿豆侠3 小时前
力扣HOT100之多维动态规划:1143. 最长公共子序列
算法·leetcode·动态规划
珂朵莉MM3 小时前
2021 RoboCom 世界机器人开发者大赛-高职组(初赛)解题报告 | 珂学家
java·开发语言·人工智能·算法·职场和发展·机器人
fail_to_code4 小时前
递归法的递归函数何时需要返回值
算法