力扣刷题-剑指offer-06-从尾到头打印链表

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 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)

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值