Java merges 2 ordered linked lists (2 linked lists contain duplicate elements)

Title description

Merging two ordered linked lists into a new linked list requires that the new linked list is generated by splicing the nodes of the two linked lists, and the new linked list is still in order after the merger.

Example 1

enter

{1},{2}

return value

{1,2}

Example 2

enter

{2},{1}

return value

{1,2}

Example 3

enter

{1,2},{1}

return value

{1,1,2}
import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param l1 ListNode类 
     * @param l2 ListNode类 
     * @return ListNode类
     */
    public ListNode mergeTwoLists (ListNode l1, ListNode l2) {
        
        if(l1 == null){
            return l2;
        }
        
        if(l2 == null){
            return l1;
        }
        
        ListNode head = new ListNode(-1);
        ListNode headTemp = head;
        ListNode node1 = l1;
        ListNode node2 = l2;
        
        while(node1!=null && node2!=null){
            
            //2个链表中含重复元素
            if(node1.val <= node2.val){
                head.next = node1;
                head = node1;
                node1 = node1.next;
            }else if(node1.val > node2.val){
                head.next = node2;
                head = node2;
                node2 = node2.next;
            }
        }
        
        //链表1长度>链表2长度 链表2遍历完了
        if(node1!=null){
            head.next = node1;
        }
        
        //链表1长度<链表2长度 链表1遍历完了
        if(node2!=null){
            head.next = node2;
        }
        
        return headTemp.next;
    }
}

 

Guess you like

Origin blog.csdn.net/luzhensmart/article/details/112727625