21. Merge Two Sorted Lists

来源:互联网 发布:数据化人生txt 编辑:程序博客网 时间:2024/06/05 03:14

题目:https://leetcode.com/problems/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 res;        if(l1.val<=l2.val)        {   res = l1;            while(l1!=null&&l2!=null)            {                if(l1.next==null&&l1.val<=l2.val){                    l1.next = l2;                    return res;                }                else if(l1.val<=l2.val&&l1.next.val>l2.val)                {                    ListNode t1 = l1.next;                    ListNode t2 = l2.next;                    l1.next = l2;                    while(t1!=null&&t2!=null&&(t2.val<=t1.val))                    {                        l2 = l2.next;                        t2 = t2.next;                    }                    l2.next = t1;                    l1 = t1;                    l2 = t2;                }                else                    l1 = l1.next;            }        }        else        {            res = l2;            while(l1!=null&&l2!=null)            {                if(l2.next==null&&l2.val<=l1.val)                {                    l2.next = l1;                    return res;                }                else if(l2.val<=l1.val&&l2.next.val>l1.val)                {                    ListNode t1 = l1.next;                    ListNode t2 = l2.next;                    l2.next = l1;                    while(t1!=null&&t2!=null&&(t1.val<=t2.val))                    {                        l1 = l1.next;                        t1 = t1.next;                    }                    l1.next = t2;                    l1 = t1;                    l2 = t2;                }                else                    l2 = l2.next;            }        }        return res;    }}1ms代码写的有点乱,而且重复率大!!
0 0