剑指offer JZ15:反转链表(双指针,递归,妖魔化的双指针)

我清晰记得,以前在数据结构课上,老师和我们说:涉及到链表的操作,一定要在纸上把过程先画出来,再写程序。

现在想想,这句话简直就是真理!

方法一:好理解的双指针

1.1 解题思路

  • 定义两个指针: prepre 和 curcur ;prepre 在前 curcur 在后。

  • 每次让 prepre 的 nextnext 指向 curcur ,实现一次局部反转

  • 局部反转完成之后, prepre 和 curcur 同时往前移动一个位置

  • 循环上述过程,直至 prepre 到达链表尾部

1.2 动态图解

img

1.3 代码

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode cur = null;
        ListNode pre = head;
        while(pre != null){
            ListNode temp = pre.next;
            pre.next = cur;
            cur = pre;
            pre = temp;
        }
        return cur;
    }
}

方法二:简洁的递归

2.1 解题思路

使用递归函数,一直递归到链表的最后一个结点,该结点就是反转后的头结点,记作 ret .此后,每次函数在返回的过程中,让当前结点的下一个结点的 next 指针指向当前节点。同时让当前结点的 next 指针指向 NULL ,从而实现从链表尾部开始的局部反转当递归函数全部出栈后,链表反转完成。

2.2 动态图解

img

2.3 代码

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null ||head.next == null){
            return head;
        }
        ListNode temp = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return temp;
    }
}

方法三:妖魔化的双指针

3.1 解题思路

  • 原链表的头结点就是反转之后链表的尾结点,使用 head 标记 .

  • 定义指针 cur,初始化为head .

  • 每次都让 head 下一个结点的 next 指向 cur ,实现一次局部反转

  • 局部反转完成之后,cur 和 head 的 next 指针同时 往前移动一个位置

  • 循环上述过程,直至 curcur 到达链表的最后一个结点 .

3.2 动态图解

img

3.3 代码

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null) return null;
        ListNode cur = head;
        while(head.next != null){
            ListNode temp = head.next.next;
            head.next.next = cur;
            cur = head.next;
            head.next = temp;
        }
        return cur;
    }
}

img

最后

希望以上讲解能帮助您理解链表的反转过程。但无论是文字描述,还是动图演示,都比不了自己在纸上对着代码画一遍来得深刻。

至此,您已经掌握了链表反转的三种实现方式,

疑问

用栈的出入栈为什么不行?

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        Stack<ListNode> stack = new Stack<>();
        int count =0;
        while(head != null){
            stack.push(head);
            head = head.next;
            count++;
        } 
        ListNode newList = stack.pop();
        while(--count-1 > 0){
            newList.next = stack.pop();
        }
        return newList;
    }
}

报错:Error - Found cycle in the ListNode

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

是我,Zack

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

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

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

打赏作者

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

抵扣说明:

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

余额充值