24. 反转链表

image.png

思路:三指针

pre、cur、curNext

  • 初始化:
    image.png
  • 第一个节点指向null
    image.png
  • cur.next指向pre
    image.png
  • 移动+cur.next指向pre
    image.png
    image.png
  • 直到curNext是空+还需要一次cur.next指向pre,返回cur
    image.png
    image.png
  • 或者直到cur是空,返回pre
    image.png

操作:

image.png

思路:递归

  • 返回条件:head==null||head.next==null
  • 递归体:
    cur的下一个节点的next指针指向cur
    cur的next指针指向null
    image.png
    image.png
    image.png

操作:

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

MeeWoW
18 声望1 粉丝

加油