LeetCode - 206. Reverse Linked List | Lacerta

206. Reverse Linked List

解法I - Iterative

实现
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    let last = null;
    while (head !== null) {
        const next = head.next;
        head.next = last;
        last = head;
        head = next;
    }

    return last;
};

解法II - Recursive

实现

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function (head) {
    if (head === null || head.next === null) {
        return head;
    }

    const h = reverseList(head.next);
    head.next.next = head;
    head.next = null;

    return h;
};