LeetCode 86. Partition List

๐Ÿ—“๏ธ Daily LeetCoding Challenge August, Day 15

Linked List

Linked List ๋ฌธ์ œ๋Š” ์ฒ˜์Œ ํ’€์–ด๋ณธ๋‹ค. ๊ฐ„์ ‘์ ์œผ๋กœ array์„ ์ด์šฉํ•ด์„œ ๋น„์Šทํ•˜๊ฒŒ๋Š” ํ’€์–ด๋ดค์ง€๋งŒ, linked list ์ž์ฒด๋ฅผ ์‚ฌ์šฉํ•ด๋ณธ๊ฑด ์ด๋ฒˆ์ด ์ฒ˜์Œ. ๋ฌธ์ œ์—์„œ ๋–กํ•˜๋‹ˆ ListNode๊ฐ€ ์ •์˜๋˜์–ด ์žˆ์–ด์„œ ๋งŽ์ด ๋‹นํ™ฉํ–ˆ๋‹ค. ์–ด๋–ป๊ฒŒ ๊ฐ’์„ ๋ถˆ๋Ÿฌ์˜ค๋Š”์ง€์กฐ์ฐจ ๋ง์„ค์ด๊ฒŒ ๋˜์—ˆ๋‹ค. ์˜ˆ์ œ๋ฅผ ์ด์šฉํ•ด์„œ ์‹ค์ œ linked list์„ ๊ทธ๋ฆฌ๋ฉด์„œ ํ’€์–ด๋ณด๋‹ˆ๊นŒ ์ดํ•ด๊ฐ€ ์ž˜ ๋˜์—ˆ๋‹ค.

๋‚˜์˜ ํ’€์ด

Linked List๋Š” ๋ชฉ๊ฑธ์ด์ฒ˜๋Ÿผ ๊ฐ Node๊ฐ€ ๊ผฌ๋ฆฌ์— ๊ผฌ๋ฆฌ๋ฅผ ๋ฌด๋Š” ํ˜•ํƒœ์˜ ์ž๋ฃŒ๊ตฌ์กฐ์ด๋‹ค. array์™€๋Š” ๋‹ค๋ฅด๊ฒŒ index๊ฐ€ ์ •ํ•ด์ง€์ง€ ์•Š๊ณ  ๊ฐ Node๋Š” val ๋ฐ์ดํ„ฐ ํ•„๋“œ์™€ ๋‹ค์Œ Node๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” *next ๋งํฌ ํ•„๋“œ๋ฅผ ๊ฐ€์ง„๋‹ค. ๋น„์—”๋‚˜์†Œ์‹œ์ง€์ฒ˜๋Ÿผ ์ค„์ค„์ด ์—ฎ์–ด๋‚ด๋ฉด linked list๊ฐ€ ์™„์„ฑ๋œ๋‹ค. index ๊ณ ๋ ค๋ฅผ ํฌ๊ฒŒ ํ•˜์ง€ ์•Š์•„๋„ ๋ผ์„œ ๋น„๊ต์  ๊ฐ„๋‹จํ•˜๊ฒŒ ํ’€์–ด๋‚ผ ์ˆ˜ ์žˆ๋‹ค.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        // head->1->4->3->2->5->2

        ListNode* curr = head;
        ListNode* less_head = new ListNode(0); // dummy node (node < x)
        ListNode* less_tail = less_head; // less tail pointer
        ListNode* large_head = new ListNode(0); // dummy node (node >= x)
        ListNode* large_tail = large_head; // large tail pointer

        while (curr != nullptr){
            if (curr -> val < x){
                less_tail -> next = new ListNode(curr -> val);
                less_tail = less_tail -> next; // move tail pointer
            } else{
                large_tail -> next = new ListNode(curr -> val);
                large_tail = large_tail -> next; // move tail pointer
            }
            curr = curr -> next; // to the next node
        }

        // result
        // less_head->0->1->2->2
        // large_head->0->4->3->5

        less_tail -> next = large_head -> next;
        // concatenate less and large List
        // less_head->0->1->2->2->4->3->5        

        return less_head -> next;
        // 1->2->2->4->3->5
    }
};