Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]
Input: l1 = [], l2 = []
Output: []
Input: l1 = [], l2 = [0]
Output: [0]
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
struct ListNode *L;
struct ListNode *p;
// example 2) 둘 다 null 이면 null
if (l1 == NULL && l2 == NULL)
{
return NULL;
}
// example 3) 둘 중 하나가 null이면 다른 하나를 리턴
if(l1 == NULL && l2 != NULL)
{
return l2;
}
if(l2 == NULL && l1 != NULL)
{
return l1;
}
// 우선 젤 작은 값이 있는 리스트를 L로 지정
if(l1->val < l2->val)
{
L = l1;
l1 = l1->next;
}
else
{
L = l2;
l2 = l2->next;
}
// L이 next로 움직이니까 맨앞자리를 p가 나타냄
p = L;
// 자기자리 찾아서 merge
while (l1 != NULL && l2 != NULL) {
if (l1->val < l2->val) {
L->next = l1;
L = l1;
l1 = l1->next;
}
else {
L->next = l2;
L = l2;
l2 = l2->next;
}
}
// 남은 건 뒤에 갖다 붙임
if (l1 != NULL)
{
L->next = l1;
}
else //if (l2 != NULL)
{
L->next = l2;
}
return p;
}
문제 보자마자 든 생각은 Merge Sort !!!!!
며칠 전 정리했던 sort 들에 감사했다..
sort 빼고 merge 함수만 갖다쓰면 굿~
// example 2) 둘 다 null 이면 null if (l1 == NULL && l2 == NULL) { return NULL; } // example 3) 둘 중 하나가 null이면 다른 하나를 리턴 if(l1 == NULL && l2 != NULL) { return l2; } if(l2 == NULL && l1 != NULL) { return l1; }
이 부분은 더 간단히 하려면
if(l1 == NULL) { return l2; } if(l2 == NULL) { return l1; }
이게 더 나을듯