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;
}
相关推荐
消失的旧时光-194311 分钟前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww27 分钟前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
你怎么知道我是队长1 小时前
C语言---循环结构
c语言·开发语言·算法
艾醒1 小时前
大模型面试题剖析:RAG中的文本分割策略
人工智能·算法
苏小瀚2 小时前
[数据结构] 排序
数据结构
纪元A梦3 小时前
贪心算法应用:K-Means++初始化详解
算法·贪心算法·kmeans
_不会dp不改名_4 小时前
leetcode_21 合并两个有序链表
算法·leetcode·链表
mark-puls4 小时前
C语言打印爱心
c语言·开发语言·算法
Python技术极客4 小时前
将 Python 应用打包成 exe 软件,仅需一行代码搞定!
算法
睡不醒的kun4 小时前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划