harrytothemoon / leetcodeAplus

Leetcode meeting note
2 stars 0 forks source link

[24] Swap Nodes in Pairs #75

Open harrytothemoon opened 3 years ago

harrytothemoon commented 3 years ago

雖然寫過,但自己從頭寫還是想不太出來QQ

var swapPairs = function(head) {
    if(!head) return null
    if(!head.next) return head

    let prev = null
    const start = head.next

    while (head && head.next) {
        const next = head.next
        const secondNext = head.next.next
        head.next = secondNext
        next.next = head
        if(prev) prev.next = next
        prev = head
        head = secondNext
    }

    return start;
};
tsungtingdu commented 3 years ago
var swapPairs = function(head) {
    if (head === null) return null
    if (head !== null && head.next === null) return head

    let n = head.next
    head.next = swapPairs(head.next.next)
    n.next = head
    return n
};