leetcode Merge Two Sorted Lists

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.

1,注意从新定义listnode后,要将头存一下,

2,头是自己定义的,返回时记得加上.next

public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
       if(l1==null&&l2==null){
            return null;
        }
        ListNode result=new ListNode(0);
        ListNode ww=result;
        while(l1!=null&&l2!=null){
            if(l1.val<l2.val){
                result.next=l1;
                l1=l1.next;
            }
            else{
                result.next=l2;
                l2=l2.next;
            }
            result=result.next;
        }
        if(l1!=null){
            result.next=l1;
        }
        else{
            result.next=l2;
        }
        return ww.next;
    }
}

 

posted @ 2014-11-03 08:23  lilyfindjob  阅读(92)  评论(0编辑  收藏  举报