250630

lililllilillll·2025년 6월 30일

개발 일지

목록 보기
218/350

✅ What I did today


  • LeetCode


⚔️ LeetCode


21. Merge Two Sorted Lists

        // ListNode* l3 = new ListNode(-101);
        // ListNode* start = l3;
        // ListNode* prev = l3;
        // while(l1 != nullptr || l2 != nullptr)
        // {
        //     int l1val = (l1) ? l1->val : 101;
        //     int l2val = (l2) ? l2->val : 101;
        //     if(l1val < l2val)
        //     {
        //         l3->val = l1val;
        //         l1 = l1->next;
        //     }
        //     else
        //     {
        //         l3->val = l2val;
        //         l2 = l2->next;
        //     }
        //     prev = l3;
        //     l3->next = new ListNode();
        //     l3 = l3->next;
        // }
        // prev->next = nullptr;
        // if(l3->val == -101) start = nullptr;
        // return start;
       ListNode dummy(0);
        ListNode* tail = &dummy;
        
        // While both lists have nodes
        while (list1 && list2) {
            if (list1->val <= list2->val) {
                tail->next = list1;  // Attach list1 node
                list1 = list1->next; // Move list1 forward
            } else {
                tail->next = list2;  // Attach list2 node
                list2 = list2->next; // Move list2 forward
            }
            tail = tail->next; // Move tail forward
        }
        
        // Attach remaining nodes (only one of these will be non-null)
        tail->next = list1 ? list1 : list2;
        
        // Return merged list, skipping dummy node
        return dummy.next; 

노드를 새로 만드는게 아니라 기존 노드를 엮는 식으로 하는 풀이가 더 쉬웠다

profile
너 정말 **핵심**을 찔렀어

0개의 댓글