当前位置:网站首页>[leetcode refers to offer 25. Merge two sorted linked lists (simple)]

[leetcode refers to offer 25. Merge two sorted linked lists (simple)]

2022-04-23 21:21:00 Minaldo7

subject :

Enter two ascending ordered linked lists , Merge these two linked lists and make the nodes in the new linked list still be sorted incrementally .

Example 1:

Input :1->2->4, 1->3->4
Output :1->1->2->3->4->4
Limit :

0 <= Chain length <= 1000

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

The problem solving process :

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
    
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    
        if(l1 == null && l2 != null) 
            return l2;
        if(l1 != null && l2 == null)
            return l1;
        if(l1 == null || l2 == null)
            return null;
        ListNode pre = new ListNode(-1);
        ListNode head = pre;
        while(l1 != null && l2 != null){
    
            if(l1.val > l2.val){
    
                pre.next = l2;
                pre = pre.next;
                l2 = l2.next;
            }else{
    
                pre.next = l1;
                pre = pre.next;
                l1 = l1.next;
            }
        }
        pre.next= l1==null ? l2:l1;
        return head.next;
    }
}

Execution results :

 Insert picture description here

版权声明
本文为[Minaldo7]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/111/202204210544479170.html