21. 合并两个有序链表 + 链表合并

21. 合并两个有序链表

LeetCode_21

题目描述

解法一:迭代法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode now = new ListNode(), newnow = now;//注意这里不能直接用now作为迭代的指针,newnow相当于临时变量,是会跟着l1和l2变化的,而最后需要返回now.next,这是不会改变的。
        ListNode temp1 = l1, temp2 = l2;
        while(temp1 != null && temp2 != null){
            if(temp1.val <= temp2.val){
                newnow.next = temp1;
                temp1 = temp1.next;
            }else {
                newnow.next = temp2;
                temp2 = temp2.next;
            }
            newnow = newnow.next;
        }
        newnow.next = temp1 == null ? temp2 : temp1;//注意这里不需要循环,直接将其连接在后面即可
        return now.next;
    }
}

方法二:递归法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1 == null)
            return l2;
        else if(l2 == null)
            return l1;
        else if(l1.val <= l2.val){
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        }else{
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }
}

posted @ 2021-03-10 21:04  Garrett_Wale  阅读(68)  评论(0编辑  收藏  举报