输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这个题很简单,就当熟悉链表了
因为要从尾打印,所以最好可以让指针倒着走,但是单链表没有前指针,这时候,就想到了栈,可以先进后出,C++的话比较简单,C标准库没有栈,那就写个简单的代替,因为题中给了链表最大长度,用固定数组大小就可以了。
C++直接用stack就行了
这里上C代码
上代码,
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
#define MAX_SIZE 10000
typedef struct{
int val[MAX_SIZE];
int topIndex;
}stack_c;
int* reversePrint(struct ListNode* head, int* returnSize){
*returnSize = 0;
if (head == NULL) return NULL;
struct ListNode *list_ptr = head;
stack_c stack;
stack.topIndex = 0;
while(list_ptr != NULL){
(*returnSize) ++;
stack.val[stack.topIndex++] = list_ptr->val;
list_ptr = list_ptr->next;
}
int* res_array = (int*)malloc((*returnSize)*sizeof(int));
for(int i = 0; i <(*returnSize) ;i++){
res_array[i] = stack.val[--stack.topIndex];
}
return res_array;
}