剑指offer--JZ6 从尾到头打印链表

我写不出来,参考别人的代码后理清思路后再写的C语言版本,代码如下:

#include <stdio.h>
#include <stdlib.h>

// 单链表结点
struct ListNode {
    int val;
    struct ListNode* next;
};

// 在链表末尾插入结点
void append(struct ListNode** head, int val) {
    struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
    newNode->val = val;
    newNode->next = NULL;

    if (*head == NULL) {
        *head = newNode;
    } else {
        struct ListNode* curr = *head;
        while (curr->next != NULL) {
            curr = curr->next;
        }
        curr->next = newNode;
    }
}

// 从尾到头返回链表节点值的数组
int* reversePrint(struct ListNode* head, int* returnSize) {
    // 统计链表节点数目
    int count = 0;
    struct ListNode* curr = head;
    while (curr != NULL) {
        count++;
        curr = curr->next;
    }

    // 创建结果数组
    int* result = (int*)malloc(sizeof(int) * count);
    *returnSize = count;

    // 将链表节点值倒序存入数组
    curr = head;
    for (int i = count - 1; i >= 0; i--) {
        result[i] = curr->val;
        curr = curr->next;
    }

    return result;
}

int main() {
    struct ListNode* head = NULL;

    // 在链表末尾插入结点
    append(&head, 1);
    append(&head, 2);
    append(&head, 3);

    int size;
    int* result = reversePrint(head, &size);

    // 打印结果数组
    for (int i = 0; i < size; i++) {
        printf("%d ", result[i]);
    }
    printf("\n");

    // 释放内存
    free(result);

    return 0;
}

最难理解的是创建结果数组那里。我竟然不知道有这种语法。我看了老半天。malloc动态申请的内存可以看作数组使用,而且能使用数组的方式来访问元素。

int* result = (int*)malloc(sizeof(int) * count);
result[i] = curr->val;

大致讲解下整体思路:

1.创建一个头结点head

2.利用尾插法开始插入结点,把值传入新结点空间中,然后修改next指针为空

如果头结点为空,那么将头节点指向新结点,如果不为空,创建一个新指针curr开始遍历找到末尾结点并且让末尾结点的next指针指向新结点

3.算出结点总数

4.通过Malloc动态创建一个结果数组。并将结点总数传入main函数的局部变量以便后续遍历。

5.将正向遍历链表的值反向插入数组中

6.for循环正向遍历数组得到反向的链表值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值