LeetCode206 反转链表

迭代法思路
  1. 定义两个指针: pre 和 cur;pre 在右 cur 在左,初始cur指向NULL,pre指向第一个结点
  2. 每次让 pre 的 next指向 cur ,实现一次局部反转
  3. 局部反转完成之后, pre 和 cur同时往前移动一个位置,
  4. 循环上述过程,直至 pre到达链表尾部
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* pre=NULL;
        ListNode* cur = head;
        
        while(cur!=NULL)
        {
            ListNode* after = cur->next;
            cur->next = pre;
            pre = cur;
            cur = after;
        }
        return pre;
    }
};


递归反转链表

迭代的思想比较直观,那么递归如何理解呢? 同时,这也是递归的核心。
我们要知道函数是要干嘛的:

输入一个节点 head ,将head为头的链表反转,并返回反转之后的头结点。

在这里插入图片描述

结合函数定义,看着上面的图(图来自labuladong算法笔记),可以reverseList(head.next) 就相当于把除第一个结点之外的剩余链表反转并得到头节点,此时就剩第一个结点没反转了,执行

head.next.next = head;
head.next = null;

结合前面分析,上面两行代码自己意会应该问题不大啦

Java实现
class Solution {
    public ListNode reverseList(ListNode head) {
        // 递归终止条件
        if(head == null || head.next == null)
        {
            return head;
        }
        ListNode r = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return r;
    }
}
C++实现
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head == nullptr || head->next == nullptr) return head;

        ListNode* res = new ListNode();
        res->next = reverseList(head->next);
        head->next->next = head;
        head->next = nullptr;

        return res->next;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值