Pages

Wednesday 2 August 2023

LeetCode - 24 - Swap Nodes in Pairs

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs = function(head) {
    if (head == null) {
        return null;
    }
    if (head.next == null) {
        return head;
    }
    var newHead = head.next;
    var nextElements = swapPairs(newHead.next);
    head.next = nextElements;
    newHead.next = head;
    return newHead;
};

No comments:

Post a Comment