iT邦幫忙

2025 iThome 鐵人賽

DAY 16
0
自我挑戰組

LeetCode 每日任務系列 第 16

LeetCode Day16

  • 分享至 

  • xImage
  •  

21. Merge Two Sorted Lists

優化版

想法:
當list為空離開迴圈
是: current.next = (list1==null ? list2:list1)
否:繼續執行null前的數值判斷

——>先判斷數值,再null


程式碼:

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode dummy = new ListNode(0); //先生成最開始用來接到第一個node的dummy node
        ListNode current = dummy;         //current node用來做遍歷使用
        while( list1 != null && list2 != null){

            if (list1.val <= list2.val){ 
                current.next = list1;  //比較小的節點接到current的next上面
                list1 = list1.next;    //對應的list指標往下走
            } else {
                current.next = list2;  
                list2 = list2.next;
            }
            current = current.next;   //current指標往下走
        
        } 
        current.next = (list1==null ? list2:list1);
        return dummy.next;
    }
}

A == B ? A : B
(若真取A;假取B)

while( list1 != null && list2 != null)
——>當其中1個list為空立即離開,因此只先判斷null前的數值大小並排列

當其1個list為空,用其判斷
current.next = (list1==null ? list2:list1)
——>可減少判斷時間,簡潔明瞭


上一篇
LeetCode Day15
下一篇
LeetCode Day17
系列文
LeetCode 每日任務18
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言