1. 程式人生 > >劍指 Offer - 16:合併兩個排序連結串列

劍指 Offer - 16:合併兩個排序連結串列

題目描述

輸入兩個單調遞增的連結串列,輸出兩個連結串列合成後的連結串列,當然我們需要合成後的連結串列滿足單調不減規則

題目連結:https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337

public class Solution {
    public ListNode Merge(ListNode list1, ListNode list2) {
        if (list1 == null) return list2;
        if (list2 == null) return
list1; // 遞迴 ListNode head = null; ListNode current = null; while (list1 != null && list2 != null) { if (list1.val <= list2.val) { if (head == null) { head = current = list1; } else { current.
next = list1; current = current.next; } list1 = list1.next; } else { if (head == null) { head = current = list2; } else { current.next = list2; current =
current.next; } list2 = list2.next; } } if (list1 == null) current.next = list2; else current.next = list1; return head; } }