Problem

Merge Two Sorted Lists

Approach

  1. It’s a good practice to fake a head node of the last linked list and then we can iterate the two linked list and compare their head nodes’ value

Code

/**
 * 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 ans = new ListNode(0);
        ListNode backupAns = ans;
        while(l1 != null || l2 != null){
            if(l1 != null && l2 != null){
                if(l1.val <= l2.val){
                    ans.next = l1;
                    l1 = l1.next;
                } else {
                    ans.next = l2;
                    l2 = l2.next;
                }
            } else if(l1 != null){
                ans.next = l1;
                break;
            } else {
                ans.next = l2;
                break;
            }
            ans = ans.next;
        }
        return backupAns.next;
    }
}