剑指offer(3)--单链表反转

题目:反转单链表

方法:

①先将链表中的元素全部放入vector容器中,再用reverse反转容器

class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
    vector<int> ret;
    while (head) {
        ret.push_back(head->val);
        head = head->next;
    }        
    std::reverse(ret.begin(), ret.end());
    return ret;
}
};

②先反转链表,再放进容器中

注意涉及反转链表时,考虑将pre指向空,将cur指向链表的head,这样就能解决头结点反转后指向空的问题,如果是下面的第二种指法,就

class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        ListNode* pre=nullptr;
        ListNode* cur=head;
        ListNode* tmp=cur->next;
        while(cur){
            tmp=cur->next;
            cur->next=pre;
            pre=cur;
            cur=tmp;
        }
        vector<int> ret;
        while(pre){
            ret.push_back(pre->val);
            pre=pre->next;
        }
        return ret;
    }
};

未解问题:段错误:您的程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起

class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        ListNode* pre=head;
        ListNode* cur=head->next;
        ListNode* tmp;
        while(cur){
            tmp=cur->next;
            cur->next=pre;
            pre=cur;
            cur=tmp;
        }
        head->next=nullptr;
        vector<int> ret;
        while(pre){
            ret.push_back(pre->val);
            pre=pre->next;
        }
        return ret;
    }
};

③递归调用printListFromTailToHead()

相比前两种方法,递归调用所占的内存明显较小
图解
1.递归调用函数的返回值是递归的核心
2.此处将head=head->next放到了参数中

class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
    vector<int> ret;
        if(!head) return ret;
        //此处将head=head->next放到了参数中
        ret = printListFromTailToHead(head->next);
        ret.push_back(head->val);
        return ret;
}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值