21. Merge Two Sorted Lists

来源:互联网 发布:深夜解莫软件 编辑:程序博客网 时间:2024/06/06 18:07

这道题,有点印象,大概思路就是原链头删,新链尾加,在原链头删的时候需要判断value大小。。。

秒了一眼之前代码,略为繁琐,这次写简单点,先new 一个 dummy node,这样会好处理很多。。。


/** * 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&&l2!=null) return l2;        else if(l2==null&&l1!=null ) return l1;        else if(l1==null&&l2==null) return null;        else{            ListNode head;   // wrong: ListNode head= new ListNode(); // even constructor w/o any para should be explicitly specified            ListNode tail;            // initiate head and tail to the min of the first node in l1 and l2            if(l1.val<=l2.val){                head=l1;                tail=l1;                l1=l1.next;            }else{                head=l2;                tail=l2;                l2=l2.next;            }                        while(l1!=null&&l2!=null){  // only in this case, I can compare the val                if(l1.val<=l2.val){                    tail.next=l1;                    tail=tail.next;//!!!! Damn, I forget this!!!                     l1=l1.next;                }else{                    tail.next=l2;                    tail=tail.next;                    l2=l2.next;                }            }            // exiting while loop, only two case: one of them is null, cannot be both be null, since only one seq updates one time.            if(l1==null) tail.next=l2;            else if(l2==null) tail.next=l1;            return head;            }    }}

今天的代码简洁很多,主要还是思路清楚多了。。。过去两周没有白过,即使最后GOOGLE和FB都挂了,也没有关系,跟两周前相比,水平有明显提升。。after a month, I am totally another person, hahaha~~

下面的代码,两点:1,用了dummy,所以不用处理l1或者l2 的头部位置;2,通过一个while loop的条件,概括了普遍的情形,进行老链头删和新链尾加。。。


/** * 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) {        ListNode dummy= new ListNode(0);        ListNode curr=dummy;                while(l1!=null && l2!=null){            if(l1.val<l2.val){                curr.next=l1;                curr=curr.next; // 唯一bug,忘了这一句                l1=l1.next;            }            else{                curr.next=l2;                curr=curr.next;                l2=l2.next;            }        }        curr.next= l1==null?l2:l1;        return dummy.next;            }}





0 0