Java solution 1ms 中文注解


  • -2
    M
      if you need explain in English ,reply me
      /**
        	 * 有点长,但是比较容易理解,分三步:
        	 * 1.如果l1,l2的排序方式不一样,逆序了
        	 * 2.按l1的排序方式向结果节点(result)add l1,l2的节点
        	 * 3.把剩下的节点加入result链表
        	 */
        	public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        		if(l2 == null) return l1;
        		if(l1 == null) return l2;
        		boolean up = true;//判断l1的排序方式  Increase or decrease
        		ListNode result = new ListNode(9527);
        		ListNode head = null;
        		if(l1.next != null && l2.next != null){
        			if(l1.val > l1.next.val)
        				up =false;
        			if ((l1.val > l1.next.val && l2.val < l2.next.val) 
        					|| (l1.val < l1.next.val && l2.val > l2.next.val)) {
        				while(l2 != null){
        					ListNode temp = l2;
        					l2 = l2.next;
        					temp.next = head;
        					head = temp;
        				}
        				l2 = head;
        			}
        		}
        		head = result;
        		if(up){
        			while(l1 != null && l2 != null){			 
        				if (l1.val <= l2.val) {
        					head.next = l1;
        					l1 = l1.next;
        					head = head.next;
        				}
        				else {
        					head.next = l2;
        					l2 = l2.next;
        					head = head.next;
        				}
        			}
        		}
        		else {
        			while(l1 != null && l2 != null){			 
        				if (l1.val >= l2.val) {
        					head.next = l1;
        					l1 = l1.next;
        					head = head.next;
        				}
        				else {
        					head.next = l2;
        					l2 = l2.next;
        					head = head.next;
        				}
        			}
        		}
        		while(l1 != null){
        			head.next = l1;
        			l1 = l1.next;
        			head = head.next;
        		}
        		while(l2 != null){
        			head.next = l2;
        			l2 = l2.next;
        			head = head.next;
        		}
        		return result.next;
            }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.