Easy 21题 Merge Two Sorted Lists(必须重刷!!!)

来源:互联网 发布:贵人 知乎 编辑:程序博客网 时间:2024/05/05 11:45

QUESTION:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.



SOLUTION

/** * 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;        //we always get the small one         if (l1.val > l2.val)         {            ListNode tmp = l2;            tmp.next = mergeTwoLists(l1, l2.next);            return tmp;        }         else         {            ListNode tmp = l1;            tmp.next = mergeTwoLists(l1.next, l2);            return tmp;        }    */        if (l1 == null || l2 == null) {    return l1 == null ? l2 : l1;    }        ListNode tmp=null;        ListNode head=null;        if(l1.val>l2.val)        {            head=l2;            l2=l2.next;                    }        else        {            head=l1;            l1=l1.next;        }        tmp=head;        while(l1!=null&&l2!=null)        {            if(l1.val>l2.val)            {                tmp.next=l2;                l2=l2.next;            }            else            {                tmp.next=l1;                l1=l1.next;            }            tmp=tmp.next;            System.out.print("123");        }        if(l1==null)        {            tmp.next=l2;        }        else if(l2==null)        {            tmp.next=l1;        }        return head;    }}


0 0
原创粉丝点击