鏈表-中等:合併兩個鏈表 By Swift

  • 題目

給你兩個鏈表 list1 和 list2 ,它們包含的元素分別爲 n 個和 m 個。markdown

請你將 list1 中第 a 個節點到第 b 個節點刪除,並將list2 接在被刪除節點的位置。spa

輸入:list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002] 輸出:[0,1,2,1000000,1000001,1000002,5] 解釋:咱們刪除 list1 中第三和第四個節點,並將 list2 接在該位置。上圖中藍色的邊和節點爲答案鏈表。code

  • 思路
    • 找到 index 爲 a 位置的節點 - preA。
    • 找到 index 爲 b + 1 位置的節點 - nextB。
    • 找到 l2 的尾結點 - l2Tail。
    • 將 preA 的 next 指向 list2;l2Tail 的 next 指向 nextB 便可。
  • 代碼
class Solution {
    func mergeInBetween(_ list1: ListNode?, _ a: Int, _ b: Int, _ list2: ListNode?) -> ListNode? {
        // step1
        let preA = findPreA(list1, a)
        // step2
        let nextB = findNextB(list1, b)
        // step3
        let l2Tail = findL2Tail(list2)
        // step4 
        preA?.next = list2
        l2Tail?.next = nextB
        return list1
    }
    
    func findPreA(_ list1: ListNode?, _ a: Int) -> ListNode? {
        var cur = list1
        var step = a - 1
        while step > 0 {
            cur = cur?.next
            step -= 1
        }
        return cur
    }
    
    func findNextB(_ list1: ListNode?, _ b: Int) -> ListNode? {
        var cur = list1
        var step = b
        while step > 0 {
            cur = cur?.next
            step -= 1
        }
        
        let result = cur?.next
        cur?.next = nil
        return result
    }
    
    func findL2Tail(_ list2: ListNode?) -> ListNode? {
        var cur = list2
        while cur?.next != nil {
            cur = cur?.next
        }
        
        return cur
    }
}
複製代碼
相關文章
相關標籤/搜索