數(shù)據(jù)結構與算法 | Leetcode 21:Merge Two Sorted Lists

bicycle_journey-wallpaper

原文鏈接:https://wangwei.one/posts/java-algoDS-Merge-Two-Sorted-Linked-Lists.html

前面,我們實現(xiàn)了鏈表的 環(huán)檢測 操作,本篇來聊聊,如何合并兩個有序鏈表。

有序鏈表合并

Leetcode 21:Merge Two Sorted Lists

示例

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

使用虛假的Head節(jié)點

定義一個臨時虛假的Head節(jié)點,再創(chuàng)建一個指向tail的指針,以便于在尾部添加節(jié)點。

對ListNode1和ListNode2同時進行遍歷,比較每次取出來的節(jié)點大小,并綁定到前面tail指針上去,直到最終所有的元素全部遍歷完。

最后,返回 dummyNode.next ,即為新鏈表的head節(jié)點。

代碼

/**
 * 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) {
        ListNode dummyNode = new ListNode(0);
        ListNode tail = dummyNode;  
    
        while(true){
            
            if(l1 == null){
                tail.next = l2;
                break;
            }
            
            if(l2 == null){
                tail.next = l1;
                break;
            }
    
            ListNode next1 = l1;
            ListNode next2 = l2;
            
            if(next1.val <= next2.val){
                tail.next = next1;
                l1 = l1.next;
            }else{
                tail.next = next2;
                l2 = l2.next;
            }
            
            tail = tail.next;
        }
        
        return dummyNode.next;
        
    }
        
}

遞歸

使用遞歸的方式,代碼比遍歷看上去簡潔很多,但是它所占用的??臻g會隨著鏈表節(jié)點數(shù)量的增加而增加。

代碼

/**
 * 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) {
        
        ListNode result = null;
        
        if(l1 == null){
            return l2;
        }
        if(l2 == null){
            return l1;
        }
        
        if(l1.val <= l2.val){
            result = l1;
            result.next = mergeTwoLists(l1.next, l2);
        }else{
            result = l2;
            result.next = mergeTwoLists(l1, l2.next);
        }
        return result;
    }
    
}

參考資料

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容