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;
}
相关推荐
緈福的街口37 分钟前
【leetcode】2236. 判断根节点是否等于子节点之和
算法·leetcode·职场和发展
祁思妙想1 小时前
【LeetCode100】--- 1.两数之和【复习回滚】
数据结构·算法·leetcode
薰衣草23331 小时前
一天两道力扣(2)
算法·leetcode
小鲈鱼-1 小时前
【LeetCode4.寻找两个正序数组的中位数】二分O(log(m+n))
c++·算法
橘颂TA1 小时前
【C++】红黑树的底层思想 and 大厂面试常问
数据结构·c++·算法·红黑树
chao_7891 小时前
二分查找篇——寻找旋转排序数组中的最小值【LeetCode】
python·线性代数·算法·leetcode·矩阵
傻欣1 小时前
动态规划疑惑总结
算法·动态规划
啊我不会诶1 小时前
倍增法和ST算法 个人学习笔记&代码
笔记·学习·算法
你的冰西瓜2 小时前
C++ 中最短路算法的详细介绍
c++·算法·图论·最短路
zstar-_2 小时前
【算法笔记】6.LeetCode-Hot100-链表专项
笔记·算法·leetcode