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

LeetCode 328 - Odd Even Linked List (Medium)

by HandHand 2023. 5. 29.

 

๐Ÿ’ก ๋ฌธ์ œ

LeetCode - 328๋ฒˆ

 

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

O(1) ์˜ ๊ณต๊ฐ„ ๋ณต์žก๋„์™€ O(n) ์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ๊ฐ€์ง€๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ด์šฉํ•ด์„œ

ํ™€์ˆ˜๋ฒˆ์งธ์™€ ์ง์ˆ˜๋ฒˆ์งธ์— ์œ„์น˜ํ•œ ๋…ธ๋“œ๋ฅผ ๋ถ„๋ฆฌํ•œ ๋’ค์— ๋‘ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ด์–ด์ฃผ๋Š” ์ž‘์—…์„ ํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค.

๋ฆฌ์ŠคํŠธ์˜ ์ฒซ๋ฒˆ์งธ ๋…ธ๋“œ๋Š” ํ•ญ์ƒ ํ™€์ˆ˜๋ฒˆ์งธ ๋…ธ๋“œ์ด๊ณ  ํ™€์ˆ˜์™€ ์ง์ˆ˜๋Š” ์ˆœ์„œ๋Œ€๋กœ ๋‚˜์˜ค๋Š” ๊ฒƒ์€ ๋ช…๋ฐฑํ•œ ์‚ฌ์‹ค์ด๋‹ˆ,

์ œ์•ฝ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๊ธฐ ์œ„ํ•ด ํ•œ๋ฒˆ์˜ ๋ฆฌ์ŠคํŠธ ํƒ์ƒ‰ ๋„์ค‘์— prev ์™€ cur ํฌ์ธํ„ฐ๋ฅผ ์ด์šฉํ•ด์„œ

์ด์ „ ๋…ธ๋“œ์˜ ๋‹ค์Œ ๋…ธ๋“œ ํฌ์ธํ„ฐ๊ฐ€ ํ˜„์žฌ ๋…ธ๋“œ์˜ ๋‹ค์Œ ๋…ธ๋“œ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋„๋ก ๋ณ€๊ฒฝํ•ฉ๋‹ˆ๋‹ค.

๋˜ํ•œ ๋‘ ๋ฆฌ์ŠคํŠธ๋ฅผ ํ•ฉ์น˜๊ธฐ ์œ„ํ•œ mergePointer ๋„ ๊ฐ€์žฅ ์ตœ์‹ ์˜ ํ™€์ˆ˜๋ฒˆ์งธ ๋…ธ๋“œ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋„๋ก ํ•ฉ๋‹ˆ๋‹ค.

 

 

๋ชจ๋“  ์ˆœํšŒ๋ฅผ ๋งˆ์น˜๋ฉด mergePointer ๋กœ ๋‘ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ด์–ด์ฃผ๋ฉด๋ฉ๋‹ˆ๋‹ค.

์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ์ž…๋ ฅ๋ฐ›๋Š” ๋ฆฌ์ŠคํŠธ์™€ ๋ณ„๊ฐœ๋กœ ๋ณ„๋„์˜ ๋ฉ”๋ชจ๋ฆฌ๊ณต๊ฐ„์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ํ•ด๊ฒฐ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

 

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

/**
 * 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 oddEvenList = function(head) {
    if (!head) {
        return null
    }

    const oddListHead = head
    const evenListHead = head.next

    let order = 1
    let mergeBasePointer = null
    let cur = head, prev = null

    while (cur) {
        const isOdd = order % 2 === 1
        if (isOdd) {
            mergeBasePointer = cur
        }

        // prev pointer ๊ฐ€ ์žˆ์œผ๋ฉด cur.next ๋กœ pointer ๋ฅผ ๋ฐ”๊ฟ”์ค€๋‹ค.
        if (prev) {
            prev.next = cur.next
        }

        order += 1
        prev = cur
        cur = cur.next
    }

    if (mergeBasePointer) {
        mergeBasePointer.next = evenListHead
    }

    return oddListHead
};
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€