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

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;
        
    }
}





![BUUCTF之[ACTF2020 新生赛]BackupFile](https://i-blog.csdnimg.cn/direct/c29bddbc355b4c5692d03a954e32f517.png)












