[leetcode] Merge Two Sorted Lists

jun·2021년 3월 25일
0
post-thumbnail

유의할점

마지막 삼항 연산자 부분은 l1이 null 이거나 l2가 null이기 때문에 가능하다.

Recursion 부분 참고

풀이

Sort List의 일부

코드

C++ : 내가 짠 코드

/**
 * 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* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* dummy = new ListNode(0);
        ListNode* p = dummy;
        while(l1!=NULL&&l2!=NULL){
            if(l1->val < l2->val){
                p->next = l1;
                l1 = l1->next;
            }else{
                p->next = l2;
                l2 = l2->next;
            }
            p = p->next;
        }
        
        p->next = l1 ? l1 : l2;
        return dummy->next;
    }
};

Java : Recursion / 가독성은 좋으나 overflow 위험 존재

public ListNode mergeTwoLists(ListNode l1, ListNode l2){
		if(l1 == null) return l2;
		if(l2 == null) return l1;
		if(l1.val < l2.val){
			l1.next = mergeTwoLists(l1.next, l2);
			return l1;
		} else{
			l2.next = mergeTwoLists(l1, l2.next);
			return l2;
		}
}
profile
Computer Science / Algorithm / Project / TIL

0개의 댓글