lintcode-easy-Merge 2 Sorted Lists

Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.

Given 1->3->8->11->15->null2->null , return1->2->3->8->11->15->null.

 

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param ListNode l1 is the head of the linked list
     * @param ListNode l2 is the head of the linked list
     * @return: ListNode head of linked list
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // write your code here
        if(l1 == null)
            return l2;
        if(l2 == null)
            return l1;
        
        ListNode fakehead = new ListNode(0);
        ListNode p = fakehead;
        
        ListNode p1 = l1;
        ListNode p2 = l2;
        
        while(p1 != null || p2 != null){
            int num1 = Integer.MAX_VALUE;
            int num2 = Integer.MAX_VALUE;
            
            if(p1 != null)
                num1 = p1.val;
            if(p2 != null)
                num2 = p2.val;
            
            if(num1 < num2){
                p.next = new ListNode(num1);
                p1 = p1.next;
            }
            else{
                p.next = new ListNode(num2);
                p2 = p2.next;
            }
            p = p.next;
        }
        
        return fakehead.next;
    }
}

 

posted @ 2016-03-02 14:08  哥布林工程师  阅读(149)  评论(0编辑  收藏  举报