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.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
这道题很简单,最朴素的方法:同时依次遍历两个链表中的值,对比后取较小的值添加到新的链表,若有一个链表先结束,就将剩下的另一个链表赋值给新链表后即可。代码如下:(请注意注释)
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode cur = head;
ListNode p = l1;
ListNode q = l2;
if(p == null){//边界条件
return l2;
}
if(q == null)
return l1;
while(p!= null && q!=null){
if(p.val <= q.val){//直接赋值还是new,这里我当时不确定
cur.next = new ListNode(p.val);
p = p.next;
}else{
cur.next = new ListNode(q.val);
q = q.next;
}
cur = cur.next;
}
if(p == null){
cur.next = q;
}
if(q == null)
cur.next = p;
return head.next;//注意返回值
}
链表中有一点要注意:最后的返回值一定是一个节点。得到答案很简单,但是还有几种很有思想的解法,可以学到很多,如下: