剑指 Offer 24. 反转链表

题目

在这里插入图片描述
https://leetcode.cn/problems/fan-zhuan-lian-biao-lcof/

参考资料

https://leetcode.cn/problems/fan-zhuan-lian-biao-lcof/comments/816840
递归总结:
https://leetcode.cn/problems/fan-zhuan-lian-biao-lcof/solution/kan-bu-dong-di-gui-de-kan-guo-lai-xi-wan-1akq/
两种解法:
https://leetcode.cn/problems/fan-zhuan-lian-biao-lcof/solution/jian-zhi-offer-24-fan-zhuan-lian-biao-die-dai-di-2/

思路要点

代码

 //思想就是把链表的值存入栈中
 //再利用栈的值构建链表
 //问题在于我不会构建链表,参考了第一篇题解
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==NULL) return head;
        
        stack<int> s;
        while(head){
            s.push(head->val);
            head=head->next;
        }
        ListNode* ans=new ListNode(s.top());
        ListNode* node=ans;
        s.pop();
        while(!(s.empty())){
            
            ans->next=new ListNode(s.top());
            s.pop();
            ans=ans->next;
            
            
        }
        return node;

    }
};

递归写法 找个时间对递归总结一下

struct ListNode* reverseList(struct ListNode* head){
    if(head==NULL|| head->next==NULL) return head;
    struct ListNode* node=reverseList(head->next);
    head->next->next=head;
    head->next=NULL;
    return node;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值