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

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

方法一:好理解的双指针

1.1 解题思路

  • 定义两个指针: prepre 和 curcur ;prepre 在前 curcur 在后。
  • 每次让 prepre 的 nextnext 指向 curcur ,实现一次局部反转
  • 局部反转完成之后, prepre 和 curcur 同时往前移动一个位置
  • 循环上述过程,直至 prepre 到达链表尾部

    1.2 动态图解

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

    1.3 代码

    1. class Solution {
    2. public ListNode reverseList(ListNode head) {
    3. ListNode cur = null;
    4. ListNode pre = head;
    5. while(pre != null){
    6. ListNode temp = pre.next;
    7. pre.next = cur;
    8. cur = pre;
    9. pre = temp;
    10. }
    11. return cur;
    12. }
    13. }

    方法二:简洁的递归

    2.1 解题思路

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

    2.2 动态图解

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

2.3 代码

  1. class Solution {
  2. public ListNode reverseList(ListNode head) {
  3. if(head == null ||head.next == null){
  4. return head;
  5. }
  6. ListNode temp = reverseList(head.next);
  7. head.next.next = head;
  8. head.next = null;
  9. return temp;
  10. }
  11. }

方法三:妖魔化的双指针

3.1 解题思路

  • 原链表的头结点就是反转之后链表的尾结点,使用 head 标记 .
  • 定义指针 cur,初始化为head .
  • 每次都让 head 下一个结点的 next 指向 cur ,实现一次局部反转
  • 局部反转完成之后,cur 和 head 的 next 指针同时 往前移动一个位置
  • 循环上述过程,直至 curcur 到达链表的最后一个结点 .

    3.2 动态图解

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

    3.3 代码

  1. class Solution {
  2. public ListNode reverseList(ListNode head) {
  3. if(head == null) return null;
  4. ListNode cur = head;
  5. while(head.next != null){
  6. ListNode temp = head.next.next;
  7. head.next.next = cur;
  8. cur = head.next;
  9. head.next = temp;
  10. }
  11. return cur;
  12. }
  13. }

image.png

最后

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

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

疑问

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

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode reverseList(ListNode head) {
  11. Stack<ListNode> stack = new Stack<>();
  12. int count =0;
  13. while(head != null){
  14. stack.push(head);
  15. head = head.next;
  16. count++;
  17. }
  18. ListNode newList = stack.pop();
  19. while(--count-1 > 0){
  20. newList.next = stack.pop();
  21. }
  22. return newList;
  23. }
  24. }

报错:Error - Found cycle in the ListNode