Leet code problem 21
 Difficulty: Easy —
Given
2 linked list đã được sắp xếp list1 & list2
Expectation
Merge thành 1 list mới được sắp xếp từ list1 & list2
 Return Head của merged list
Solution
Chú thích
 resultList: Linked list kết quả
 p1: node hiện tại của list1
 p2: node hiện tại của list2
Iterative approach
- So sánh giá trị của 
p1vàp2- Thêm vào 
resultListphần tử có giá trị nhỏ hơn - Dịch chuyển 
pointercủa list có giá trị nhỏ hơn 1 đơn vị 
 - Thêm vào 
 - Nếu 
p1 != nullhoặcp2 != null, lặp lại bước 1. Ngược lại, tiếp tục với bước 3 - Thêm phần tử còn lại vào 
resultList - Trả về 
nodeđầu tiên củaresultList 
Implementation
 Code from github
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class L21_MergeTwoSortedList {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode preHead = new ListNode(-1);
        ListNode curList = preHead;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                curList.next = l1;
                l1 = l1.next;
            } else {
                curList.next = l2;
                l2 = l2.next;
            }
            curList = curList.next;
        }
        curList.next = l1 == null ? l2 : l1;
        return preHead.next;
    }
}
