题目描述
将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
解题思路
1、类似归并算法中的合并过程,多建立了额外空间
2、代码逻辑:
(1)创建一个哨兵
(2)比较链表l1 和 l2的值,哪个值小,哨兵就指向那个值
(3)如果一个链表为空,则将那一个链表直接复制过来
代码迭代
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null) return l2;
else if(l2 == null) return l1;
ListNode dummy = new ListNode(0);
ListNode curr = dummy;
while(l1 != null && l2 != null){
if(l1.val <= l2.val){
curr.next = l1;
l1 = l1.next;
}else{
curr.next = l2;
l2 = l2.next;
}
curr = curr.next;
}
curr.next = l1 == null? l2 : l1;
return dummy.next;
}
}
代码递归
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null) return l2;
if(l2 == null) return l1;
ListNode merge = null;
if(l1.val <= l2.val){
merge = l1;
merge.next = mergeTwoLists(l1.next, l2);
}else{
merge = l2;
merge.next = mergeTwoLists(l1, l2.next);
}
return merge;
}
}
参考:https://leetcode.com/problems/merge-two-sorted-lists/discuss/9715/Java-1-ms-4-lines-codes-using-recursion