LeetCode 21 question: merge two ordered linked lists merge two ascending linked lists into a new ascending linked list and return. The new linked list is composed by splicing all the nodes of the given two linked lists.

  1. Merge two ordered linked
    lists Combine two ascending linked lists into a new ascending linked list and return. The new linked list is composed by splicing all the nodes of the given two linked lists.

Example 1:

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2
输入:l1 = [], l2 = []
输出:[]
示例 3
输入:l1 = [], l2 = [0]
输出:[0]
 

prompt:

两个链表的节点数目范围是 [0, 50]
-100 <= Node.val <= 100
l1 和 l2 均按 非递减顺序 排列

Code:

/**
 * 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 headA, ListNode headB) {
    
    //两个链表头分别headA,headB;
        ListNode newHead = new ListNode(-1);//定义一个傀儡节点
        ListNode tmp =newHead;//定义一个移动的节点tmp保存往傀儡节点后面拼接的节点此时位置在傀儡节点
        while(headA !=null && headB != null){
    
    //两个都不为空
            if(headA.val > headB.val){
    
    //判断链表头val的大小
                tmp.next = headB;//保存headB
                headB = headB.next;//headB后移一位
                tmp = tmp.next;//tmp也后移一位
            }else{
    
    //headB.val大
                tmp.next = headA;//保存headA
                headA = headA.next;//headA后移一位
                tmp = tmp.next;//tmp后移一位
            }
        }
        if(headB != null){
    
    //headB为空
            tmp.next =headB;//直接是headB链表
        }
        if(headA != null){
    
    //headA为空
            tmp.next =headA;//直接是headA链表
        }
        return newHead.next;//返回链表的头,傀儡节点的下一个;
    }
}

The result passed

Guess you like

Origin blog.csdn.net/weixin_44436675/article/details/112460711