前言
题目描述:输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
一、示例

二、代码
代码如下(示例):
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* reversePrint(struct ListNode* head, int* returnSize){
int num = 0;
struct ListNode* p = (struct ListNode*)malloc(1 * sizeof(struct ListNode));
struct ListNode* q = (struct ListNode*)malloc(1 * sizeof(struct ListNode));
p = head;
q = head;
while(p) {
++num;
p = p->next;
}
*returnSize = num;
int* new_array = (int*)malloc( sizeof(int) * (num + 1) );
for(; num > 0; --num) {
new_array[num-1] = q->val;
q = q->next;
}
return new_array;
}
结果

该博客主要介绍了如何遍历一个链表并从尾到头反向返回每个节点的值。通过示例代码展示了一种实现方法,利用双指针技巧完成链表的反转打印,并将结果存储在一个数组中。
906

被折叠的 条评论
为什么被折叠?



