Notice
Recent Posts
Recent Comments
Link
«   2026/04   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
Archives
Today
Total
관리 메뉴

hwooo

LeetCode (C/C++) 86. Partition List 본문

Study/Algorithm

LeetCode (C/C++) 86. Partition List

hwooo 2024. 6. 4. 16:29

https://leetcode.com/problems/partition-list/description/


풀이

x를 기준으로 작은 값을 저장할 리스트(small)와 큰 값을 저장할 리스트(big)을 생성
주어진 리스트의 노드를 하나씩 탐색하며 x보다 작은 값이라면 small에, 큰 값이라면 big에 넣어 따로 저장 후 이를 합쳐 반환


코드

class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode* small = new ListNode();
        ListNode* big = new ListNode();

        ListNode* result = small;
        ListNode* bigResult = big;
        ListNode* now = head;

        while (now) {
            if (now->val < x) {
                small->next = now;
                small = small->next; 
            }
            else {
                big->next = now;
                big = big->next; 
            }
            now = now->next;
        }
        small->next = bigResult->next;
        big->next = NULL;
        return result->next;
    }
};