lintcode 165 合并两个排序链表

2017-08-07  本文已影响0人  jose_dl
Snip20170807_1.png
/**
 * 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 p=l1;
        ListNode q=l2;
        ListNode head=p.val<q.val?p:q;
        if(head==p){
            p=p.next;
        }else{
            q=q.next;
        }
        ListNode r = head;
       
        while(p !=null && q != null){
           if(p.val<q.val){
                r.next=p;
                r=p;
                p=p.next;
           }
           else {
                r.next=q;
                r=q;
                q=q.next;
           }
            
        }
        if(p!=null){
           r.next=p;
        }
        if(q!=null){
            r.next=q;
        }
        return head;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读