day14 leetcode-hot100-27(链表6)

21. 合并两个有序链表 - 力扣(LeetCode)

day14 leetcode-hot100-27(链表6)_第1张图片

1.  暴力法

思路

创建一个空节点,用来组装这两个链表,谁小谁就是下一个节点。

知识

创建空节点:ListNode n1 = new ListNode(-1);

具体代码
/**
 * 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 list1, ListNode list2) {
        
        ListNode l1=list1,l2=list2;
        ListNode init = new ListNode(-1);
        ListNode newCon = init;
        while(l1!=null && l2!=null){
            if(l1.val<=l2.val){
                newCon.next=l1;
                l1=l1.next;
            }
            else{
                newCon.next=l2;
                l2=l2.next;
            }
            newCon=newCon.next;
        }
        newCon.next=l1==null ? l2:l1;
        return init.next;

        
    }
}

你可能感兴趣的:(leetcode,链表,算法)