Url: https://leetcode.com/problems/merge-two-sorted-lists
Question: Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
솔직히 너무 쉬운 문제라 안올릴까 했는데 그냥 정리차원에서.. 사이즈를 알 필요도 없고, 단순히 두 개의 리스트 돌면서 그때마다 크기 비교해서 작은 순서대로 넣어주고, 나중에 끝에 다다르는 한 개가 있으면 다른 한개가 비어있지 않는다면 이를 다시 끝에 넣어주고 리턴해주면 된다. 시간복잡도는 O(n) 일듯.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode rslt = new ListNode(0);
ListNode head = rslt;
if(l1 == null && l2 == null) return null;
else if(l1 == null) return l2;
else if(l2 == null) return l1;
while(l1 != null && l2 != null){
if(l1.val > l2.val){
rslt.next = new ListNode(l2.val);
rslt = rslt.next;
l2 = l2.next;
}else{
rslt.next = new ListNode(l1.val);
rslt = rslt.next;
l1 = l1.next;
}
}
if(l1 != null){
while(l1 != null){
rslt.next = new ListNode(l1.val);
rslt = rslt.next;
l1 = l1.next;
}
}else if(l2 != null){
while(l2 != null){
rslt.next = new ListNode(l2.val);
rslt = rslt.next;
l2 = l2.next;
}
}
return head.next;
}
}


