zoukankan      html  css  js  c++  java
  • 1025. 反转链表

    题目截图:

    思路:

      静态链表。将结点的地址按链表顺序存储到 list 数组中,然后对矩阵进行部分逆置即可。注意:输入的结点不一定都在链表内。

    代码:

     1 /*
     2     1025. 反转链表
     3 */
     4 
     5 #include <stdio.h>
     6 #include <string.h>
     7 #include <math.h>
     8 #include <stdlib.h>
     9 #include <time.h>
    10 
    11 #define maxn 100001
    12 // data[i] 表示地址为 i 结点的数据
    13 // next[i] 表示地址为 i 结点的下个结点的地址
    14 // list[i] 表示按链表遍历第 i 个结点的地址 
    15 int data[maxn], next[maxn], list[maxn];
    16 
    17 // 对[a,b]进行逆置 
    18 void reverse(int a, int b) {
    19     int i;
    20     for(i=a; i<=(a+b)/2; ++i) {
    21         int temp = list[i];
    22         list[i] = list[a+b-i];
    23         list[a+b-i] = temp;
    24     }
    25 }
    26 
    27 int main() {
    28     int head, N, K, i;
    29     scanf("%d %d %d", &head, &N, &K);
    30     for(i=0; i<N; ++i) {            // 输入结点 
    31         int temp;
    32         scanf("%d", &temp);
    33         scanf("%d %d", &data[temp], &next[temp]);
    34     }
    35     // 注意:输入结点不一定都在链表内 
    36     int cnt=0;                        // 记录链表内结点数 
    37     while(head != -1) {
    38         list[cnt++] = head;            // 地址按顺序存储到  list
    39         head = next[head];
    40     }
    41     for(i=0; i<cnt-(cnt%K); i+=K) {    // 每 K 个结点逆置 
    42         reverse(i, i+K-1);
    43     }
    44     for(i=0; i<cnt-1; ++i) {        // 按格式输出 
    45         printf("%05d %d %05d
    ", list[i], data[list[i]], list[i+1]);
    46     }
    47     printf("%05d %d -1", list[i], data[list[i]]);
    48 
    49     return 0;
    50 }
  • 相关阅读:
    微信小程序上拉分页
    关于检测数据类型,三种方法(typeof,instanceof,Object.prototype.toString.call())优缺点
    如何在Devc++中配置OpenCv
    数据库系统和应用
    这是一篇测试文档
    Pandas 表格合并
    es6一些好用的方法总结
    前端面试题
    超有趣! JS是怎么计算1+2!!!
    彻底理解闭包
  • 原文地址:https://www.cnblogs.com/coderJiebao/p/PAT1025.html
Copyright © 2011-2022 走看看