Thursday, May 29, 2014

Merge Two Sorted Lists

Well, this is too easy. I think this can be solved very quickly. My answer is shown as below:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1==null) return l2;
        if (l2 == null) return l1;
        ListNode tmp1 = l1;
        ListNode tmp2 = l2;
        ListNode newHead = null;
        ListNode movingNode = null;
        while(tmp1!= null && tmp2!=null){
            if(tmp1.val <= tmp2.val){
             
                if(newHead == null){
                    newHead = tmp1;
             
                    movingNode = newHead;
                }
                else {
                    movingNode.next = tmp1;
                    movingNode = movingNode.next;
                }
                tmp1 = tmp1.next;
            }
            else{
                if(newHead == null){
                    newHead = tmp2;
                    movingNode = newHead;
                }
                else {
                    movingNode.next = tmp2;
                    movingNode = movingNode.next;
                }
                tmp2 = tmp2.next;                  
            }
        }
        if(tmp1 == null && tmp2 != null) movingNode.next = tmp2;
        else if(tmp2 == null && tmp1 != null)movingNode.next = tmp1;
     
        return newHead;
    }
}

No comments:

Post a Comment