๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 24 - Swap Nodes in Pairs (Medium)

by HandHand 2023. 2. 20.

 

๐Ÿ’ก ๋ฌธ์ œ

LeetCode -24๋ฒˆ

 

๐ŸŽฏ ํ’€์ด ๊ณผ์ •

๋’ค์—์„œ๋ถ€ํ„ฐ ๋…ธ๋“œ์˜ ์ˆœ์„œ๋ฅผ ์žฌ๊ท€์ ์œผ๋กœ ๋ณ€๊ฒฝ(swap)ํ•˜๋Š” ์š”๊ตฌ์กฐ๊ฑด์„ ๊ตฌํ˜„ํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

ํฌ์ธํ„ฐ๋ฅผ ๋ฐ”๊ฟ”์ฃผ๊ธฐ ์œ„ํ•ด ์žฌ๊ท€ํ˜ธ์ถœ ์‹œ ํ˜„์žฌ ๋…ธ๋“œ์™€ ์ด์ „๋…ธ๋“œ์— ๋Œ€ํ•œ ์ฐธ์กฐ๋ฅผ ํ•จ๊ป˜ ์ „๋‹ฌํ•˜๋„๋ก ํ–ˆ์Šต๋‹ˆ๋‹ค.

 

๐Ÿ‘จ‍๐Ÿ’ป ์ฝ”๋“œ

/**
 * 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) {

    function swap(prev, cur, step) {
        if (!cur) {
            return null
        }

        swap(cur, cur.next, step + 1)

        let newHead = cur

        if (step % 2 !== 0) {
            const nextNode = cur.next
            if (nextNode) {
                cur.next = nextNode.next
                nextNode.next = cur

                if (prev) {
                    prev.next = nextNode
                }

                newHead = nextNode
            } 
        }

        return newHead
    }

    return swap(null, head, 1)
};
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 13 - Roman to Integer (Easy)  (0) 2023.04.24
LeetCode 994 - Rotting Oranges (Medium)  (0) 2023.04.24
LeetCode 35 - Search Insert Position (Easy)  (0) 2023.02.20
LeetCode 169 - Majority Element (Easy)  (2) 2023.02.05
LeetCode 733 - Flood Fill (Easy)  (0) 2022.03.07

๐Ÿ’ฌ ๋Œ“๊ธ€