我写不出来,参考别人的代码后理清思路后再写的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.将正向遍历链表的值反向插入数组中文章来源:https://www.toymoban.com/news/detail-510362.html
6.for循环正向遍历数组得到反向的链表值文章来源地址https://www.toymoban.com/news/detail-510362.html
到了这里,关于剑指offer--JZ6 从尾到头打印链表的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!