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.

这道题是合并两个有序链表。

首先要考虑代码的鲁棒性,即如果其中一个链表为空会怎么样?两个都是空链表会怎样?
这道题和合并两个有序数组不同,因为不用预先分配大小。

最核心的是将每一次要加入merge的结点当做head来处理,这样就可以递归了,这道题主要参考了剑指offer的面试题17。

下面附上代码:

if(l1==null){
        	return l2;
        }
        if(l2==null){
        	return l1;
        }
        ListNode newListHead = null;
        if(l1.val<l2.val){
        	newListHead = l1;
        	newListHead.next = mergeTwoLists(l1.next,l2);
        }
        else{
        	newListHead = l2;
        	newListHead.next = mergeTwoLists(l1,l2.next);
        }
        return newListHead;

  

原文地址:https://www.cnblogs.com/gracyandjohn/p/4422447.html