21. Merge Two Sorted Lists

Posted 阿怪123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了21. Merge Two Sorted Lists相关的知识,希望对你有一定的参考价值。

/**
 * 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的主要内容,如果未能解决你的问题,请参考以下文章

21. Merge Two Sorted Lists

[LeetCode] 21. Merge Two Sorted Lists_Easy tag: Linked List

LeetCode(21) - Merge Two Sorted Lists

21. Merge Two Sorted Lists

21. Merge Two Sorted Lists

LintCode - Merge Two Sorted List