天天看点

21 合并两个有序链表

1. 问题描述:

将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

示例:

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

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

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/merge-two-sorted-lists

2. 思路分析:

① 其实这道题目是链表题目中比较经典的题目,在循环中当两个链表都不为空的时候遍历链表元素,使用一个前驱指针来记录上一个节点这样才好连接当前需要连接的节点(上一个节点的next指向当前较小的元素),在循环中判断两个链表当前节点的大小关系,pre节点的next指针域连接的较小的元素,当连接的是较小元素的时候,将该链表的指针往下移动一位,另外一个链表指向当前节点的指针不变

② 当退出循环之后将pre的next指针域连接到还有剩余元素的链表上即可,整体的代码难度不大

3. 代码如下:

class Solution {
   public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null && l2 != null) return l2;
        if (l1 != null && l2 == null) return l1;
        ListNode pre = null, head = null;
        while (l1 != null && l2 != null){
            if (l1.val < l2.val){
                if (pre == null){
                    pre = l1;
                    head = l1;
                }
                else  {
                    pre.next = l1;
                    pre = l1;
                }
                l1 = l1.next;
            }else {
                if (pre == null){
                    pre = l2;
                    head = l2;
                }
                else {
                    pre.next = l2;
                    pre = l2;
                }
                l2 = l2.next;
            }
        }
        if (l1 != null && pre != null) pre.next = l1;
        if (l2 != null && pre != null) pre.next = l2;
        return head;
    }
}
           

继续阅读