leetcode 21.Merge Two Sorted Lists ,java

题目:

  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.

解决方案:276ms

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
14         ListNode head = new ListNode(0);
15         ListNode newList = head;
16         
17         if(l1 == null || l2 == null){//两者有为空的情况
18             if(l1==null)
19                 return l2;
20             if(l2 == null)
21                 return l1;
22         }
23         
24         while(l1!=null && l2!=null){//两者都不为空
25             
26             if(l1.val <= l2.val){
27                 newList.next = l1;
28                 l1 = l1.next;
29             }else{// if(l1.val < l2.val)
30                 newList.next = l2;
31                 l2 = l2.next;
32             }
33             newList = newList.next;
34         }
35         while(l1!=null){
36             newList.next = l1;
37             l1 = l1.next;
38             newList = newList.next;
39         }
40         while(l2!=null){
41             newList.next = l2;
42             l2 = l2.next;
43             newList = newList.next;
44         }
45         
46         return head.next;
47     }
48 }
View Code

总结:

  这道题目很简单,就是我们以前数据结构学习的时候的一道课本上的算法代码,其实思路就在那里,很容易就想到,但是我这里犯错了,我在第一个while中把nextList = nextList.next放到了while第一句里面,当然下面的代码也就是nextList = l1;这样了,但是这样是不对的,具体原因我也没弄清楚,希望有人帮我解决问题。多谢诸位。

贴错误代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode newList = head;
        
        if(l1 == null || l2 == null){//两者有为空的情况
            if(l1==null)
                return l2;
            if(l2 == null)
                return l1;
        }
        
        while(l1!=null && l2!=null){//两者都不为空
            newList = newList.next;
            if(l1.val <= l2.val){
                newList = l1;
                l1 = l1.next;
            }else{// if(l1.val < l2.val)
                newList = l2;
                l2 = l2.next;
            }
            
        }
        while(l1!=null){
            newList.next = l1;
            l1 = l1.next;
            newList = newList.next;
        }
        while(l2!=null){
            newList.next = l2;
            l2 = l2.next;
            newList = newList.next;
        }
        
        return head.next;
    }
}

代码提示错误:

Input:     {2}, {1}
Output:    {}
Expected:  {1,2}

纠结,这个问题都没搞懂。。。

原文地址:https://www.cnblogs.com/Pillar/p/4317339.html