其他分享
首页 > 其他分享> > LeetCode 0021 Merge Two Sorted Lists

LeetCode 0021 Merge Two Sorted Lists

作者:互联网

原题传送门

1. 题目描述

2. Solution 1

1、思路分析
类似合并两个有序数组,设置两个指针分别指向两个链表的head,比较大小,把较小的结点从原始链表摘下挂到结果链表中。
2、代码实现

package Q0099.Q0021MergeTwoSortedLists;

import DataStructure.ListNode;

public class Solution1 {
    /*
      递归
      设f(l1, l2)为递归功能函数
      递归终止条件:
      f(l1, l2) = l2;  若 l1 == null
      f(l1, l2) = l1;  若 l2 == null
      递归主体:
      f(l1, l2) = l1 + f(l1->next, l2);  若 l1的结点值 小于 l2的结点值
      f(l1, l2) = l2 + f(l1, l2-> next); else
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null || l2 == null) return l1 != null ? l1 : l2;
        if (l1.val < l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }
}

3. Solution 2

1、思路分析
迭代实现

2、代码实现

package Q0099.Q0021MergeTwoSortedLists;

import DataStructure.ListNode;

public class Solution2 {
    // 迭代
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null || l2 == null) return l1 != null ? l1 : l2;
        ListNode head = new ListNode(0); // 头结点
        ListNode p = head;
        while (l1 != null && l2 != null) {     // 进入循环的条件是 与,不然,把非空的链表挂到结果链
            if (l1.val < l2.val) {
                p.next = l1;
                l1 = l1.next;
            } else {
                p.next = l2;
                l2 = l2.next;
            }
            p = p.next;
        }
        p.next = l1 != null ? l1 : l2;
        return head.next;
    }
}

标签:0021,ListNode,Two,Lists,next,l2,l1,return,null
来源: https://www.cnblogs.com/junstat/p/15987870.html