Java教程

2022-1-8-21. Merge Two Sorted Lists

本文主要是介绍2022-1-8-21. Merge Two Sorted Lists,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

合并2个有序链表

/**
 * 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) {
        if(list1 == null)
            return list2;
        if(list2 ==null)
            return list1;
        ListNode head = new ListNode();
        ListNode cur = head;
        while(list1!=null && list2!=null){
            if(list1.val < list2.val){
                cur.next = list1;
                list1 = list1.next;
            }else{
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }
        if(list1==null)
            cur.next = list2;
        if(list2==null)
            cur.next = list1;
        return head.next;
    }
}

这篇关于2022-1-8-21. Merge Two Sorted Lists的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!