LeetCode热题(JS版) - 206. 反转链表

52 阅读1分钟

题目

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

示例 1:

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

示例 2:

输入:head = [1,2]
输出:[2,1]

示例 3:

输入:head = []
输出:[]

提示:

链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000

进阶:链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题?

思路:双指针迭代法

通过循环取出pre。然后把pre挂在每个curr的next上

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function reverseList(head: ListNode | null): ListNode | null {
    let pre = null, curr = head, next = head;
    while(curr) {
        next = curr.next;
        curr.next = pre;
        pre = curr;
        curr = next;
    }
    return pre;
};

image.png

思路2:递归法

head.next.next = head;// head移到最后

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function reverseList(head: ListNode | null): ListNode | null {
    
    // 迭代法
    // let pre = null, curr = head, next = head;
    // while(curr) {
    //     next = curr.next;
    //     curr.next = pre;
    //     pre = curr;
    //     curr = next;
    // }

    // 递归法
    if(!head || !head.next) return head;
    const ret = reverseList(head.next);
    head.next.next = head;// head移到最后
    head.next = null;// 最后的next肯定要空
    return ret
};