1. 程式人生 > 其它 >21. 合併兩個有序連結串列 (雙指標)

21. 合併兩個有序連結串列 (雙指標)

技術標籤:lankerenFrequency連結串列指標JavaByteDance

LeetCode: 21. 合併兩個有序連結串列

在這裡插入圖片描述


歸併排序 >> 一條連結串列 >> 時間複雜度 >> O(nlogn)

這裡合併兩條連結串列 >> 雙指標就行,誰小接誰



雙指標

/**
 * 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 head, ListNode head2) { ListNode h1 = head, h2 = head2; if(h1 == null && h2 == null) return null; if(h1 == null) return h2; if(h2 == null) return h1; ListNode h = new ListNode(); ListNode ans =
h; while(h1 != null && h2 != null){ if(h1.val < h2.val) { h.next = h1; h1 = h1.next; } else if(h1.val >= h2.val){ h.next = h2; h2 = h2.next; } h = h.next;
} if(h1 != null){ h.next = h1; } if(h2 != null){ h.next = h2; } return ans.next; } }