首页 > 其他 > 详细

21. Merge Two Sorted Lists

时间:2016-04-04 14:41:44      阅读:144      评论:0      收藏:0      [点我收藏+]
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1==null)
            return l2;
        if(l2==null)
            return l1;
        ListNode head=null;
        ListNode t1=l1;
        ListNode tail=null;
        ListNode t2=l2;
        while(t1!=null&&t2!=null)
        {
            if(t1.val<=t2.val)
            {
                if(head==null)
                    head=t1;
                else
                    tail.next=t1;
                tail=t1;
                t1=t1.next;
                
            }
            else
            {
                if(head==null)
                    head=t2;
                else
                    tail.next=t2;
                tail=t2;
                t2=t2.next;
            }
        }
        while(t1!=null)
        {
            tail.next=t1;
            tail=t1;
            t1=t1.next;
        }
        while(t2!=null)
        {
            tail.next=t2;
            tail=t2;
            t2=t2.next;
        }
        return head;
        
    }
}

 

21. Merge Two Sorted Lists

原文:http://www.cnblogs.com/aguai1992/p/5351917.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!