【链表】LeetCode206. 反转链表

150 阅读1分钟

题目

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

示例

输入: head = [1,2,3,4,5]
输出: [5,4,3,2,1]

递归

主要思路

  1. 终止条件:head为空或者head.next为空
  2. 每次递归调用传入head.next
  3. 当递归到最后,head.next指向最后一个节点,因为是反转
  4. 所以head.next.next = head,比如:4 -> 5 变为5 -> 4
  5. 然后需要将head.next = null

代码实现

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

双链表

主要思路

  1. 创建一个新链表,头结点为newHead
  2. 遍历原链表,每个节点下一个节点指向新链表的头结点
  3. 然后更新newHead和head

代码实现

public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode newHead = null;
        while(head != null){
            ListNode node = head.next;
            head.next = newHead;
            newHead = head;
            head = node;
        }
        return newHead;
    }