剑指 Offer 06. 从尾到头打印链表 C语言


题目

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

输入:head = [1,3,2] 输出:[2,3,1]

一、思路

本题若不加其他限制条件,可以说非常简单,遍历链表并存到数组,最后逆序数组,然后输出。

二、代码

1.引入库

#include <stdio.h>
#include <malloc.h>
#include <cstring>

处理数组很标准的三个库 stdio.h是标准库 malloc.h,是用来申请数组内存的 cstring.h调用memest函数,实现数组清零。

2.具体代码

int* reversePrint(struct ListNode* head, int* returnSize){
          
   

    struct ListNode* p = head;
    int i=0;
    int num = 0;
    int swap;
    int* arr = (int*)malloc(10000 * sizeof(int));

    memset(arr, 0, 10000 * sizeof(int));
    while(p)
    {
          
   
        arr[num++] = p->val;
        p=p->next; 
    }
    for(i = 0;i < num / 2;i++)
    {
          
   
        swap = arr[i];
        arr[i] = arr[num - i - 1];
        arr[num - i - 1] = swap;
    }
    (*returnSize) = num;
    return arr;
}

总结

题目不难,但是刷题要持之以恒,不能间断啊! 链表调用数据是p->val,不是p.val。

经验分享 程序员 微信小程序 职场和发展