输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:0 <= 链表长度 <= 10000
作者:Krahets
链接:https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/5dt66m/
来源:力扣(LeetCode)
/**
- 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){
*returnSize=0;//retrunsize返回的是链表的长度
if(head==NULL)//如果输入是空链表直接结束运行
return NULL;
int stack[10001];//建立栈
int top=-1;//初始化栈指针
while(head)//将链表元素压入栈中
{
stack[++top]=head->val;//入栈操作,且栈指针上移,由0开始
head=head->next;//结点指针后移
}
int* res=(int*)malloc(sizeof(int)*(top+1));//按照栈的大小来申请空间,+1是因为栈是从0开始的
while(top!=-1)//弹栈
res[(*returnSize)++]=stack[top--];//将栈内的元素反弹至数组内,且栈指针回移
return res;
}
作者:mrggls-t
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/solution/fei-di-gui-zhan-nin-kan-wo-huan-you-ji-hui-ma-by-m/
来源:力扣(LeetCode)