第二章 链表_206. 反转链表


206. 反转链表

一、题目

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

二、遇到的问题

1. 双指针应该设置哪两个指针?

前指针 pre,和当前指针 cur。双指针不意味着代码中只能有两个指针,在某些情况下,可能会使用更多的指针来解决特定的问题。

2. 当 cur 指向 pre 后,如何让 cur 指向下一个 cur?

设置 ListNode temp = cur.next; 先将下一个 cur 保存起来。

3. 递归方法(需要单独定义)

作用:用来实现递归操作
参数:cur、pre
如何写递归方法:
1. 明确边界条件:当 cur == null 时
2. 如何递归调用方法 return reverse(cur, pre);

三、代码

1. 双指针

public class Solution {

    /**
     * 双指针法
     *
     * @param head
     * @return
     */
    public ListNode reverseList(ListNode head) {
        ListNode cur = head;
        ListNode pre = null;
        while (cur != null) {
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
}

class ListNode {
    int val;
    ListNode next;

    public ListNode() {
    }

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

2. 递归

public class Solution {

    /**
     * 递归算法
     *
     * @param head
     * @return
     */
    public ListNode reverseList1(ListNode head) {
        // 递归调用,初始的 cur 就是 head,初始的 pre 就是 null
        return reverse(head, null);
    }
	
	// 递归方法
    public ListNode reverse(ListNode cur, ListNode pre) {
        // 退出条件
        if (cur == null) {
            return pre;
        }
        // 每个节点都需要递归执行的操作
        ListNode temp = cur.next;
        cur.next = pre;
        pre = cur;
        cur = temp;
        // 递归体
        return reverse(cur, pre);
    }
}

class ListNode {
    int val;
    ListNode next;

    public ListNode() {
    }

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员_动次动次

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值