25. 合并两个排序的链表

剑指offer 25 合并两个排序的链表 LeetCode21

输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。

示例1:

输入: 1->2->4, 1->3->4
输出: 1->1->2->3->4->4

限制:

0 <= 链表长度 <= 1000

注意:本题与主站 21 题相同:https://leetcode-cn.com/problems/merge-two-sorted-lists/

解法一:从头至尾比较当前节点的大小,构建新的链表。

Java代码

/**
 * 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 p1 = l1;//用于遍历l1
        ListNode p2 = l2;//用于遍历l2
        ListNode dummy = new ListNode(0);//新链表虚拟头节点
        ListNode cur = dummy;//辅助构建新链表
        
        //两个链表都未遍历结束时,比较当前节点大小,拼接到新链表之后
        while(p1 != null && p2 != null){
    
    
            if(p1.val < p2.val){
    
    
                cur.next = p1;
                p1 = p1.next;
                cur = cur.next;
            }else{
    
    
                cur.next = p2;
                p2 = p2.next;
                cur = cur.next;
            }
        }

        //退出上面的while循环后,说明肯定是有一个链表已经遍历结束了
        if(p1 == null){
    
    
            cur.next = p2;
        }
        if(p2 == null){
    
    
            cur.next = p1;
        }
        return dummy.next;

    }
}

在这里插入图片描述

解法二:使用递归

Java代码

/**
 * 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;
        if(l1.val < l2.val){
    
    
            l1.next = mergeTwoLists(l1.next,l2);
            return l1;
        }else{
    
    
            l2.next = mergeTwoLists(l1,l2.next);
            return l2;
        }
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/YouMing_Li/article/details/114300853