Swift Mege Sort

func merge<T: Comparable>(_ left: LinkedList<T>, _ right: LinkedList<T>) -> LinkedList<T> {
    guard !left.isEmpty else {return right} // if left list is empty, return right
    guard !right.isEmpty else {return left} // if right is empty, return left
    
    var newHead: Node<T>? // declare new head
    var tail: Node<T>? // declare tail
    var currentLeft = left.head // left poiner, point to head
    var currentRight = right.head // right poiner, point to head
    
    // check which head is smaller, and set the newHead
    if let leftNode = currentLeft, let rightNode = currentRight {
        if leftNode.value < rightNode.value { // left head is smaller
            newHead = leftNode // set new head to left head
            currentLeft = leftNode.next // left pointer move forward
        } else {
            newHead = rightNode
            currentRight = rightNode.next
        }
    }
    
    tail = newHead // init tail with new head
    
    while let leftNode = currentLeft, let rightNode = currentRight { // loop while both pointer is not nil
        if leftNode.value < rightNode.value { // if left node is smaller
            tail?.next = leftNode // append left node
            currentLeft = leftNode.next // forward left pointer
        } else {
            tail?.next = rightNode
            currentRight = rightNode.next
        }
        tail = tail?.next // tail move forward
    }
    
    if let leftNodes = currentLeft { // append rest of the left list
        tail?.next = leftNodes
    }
    
    if let rightNodes = currentRight { // append rest of right list
        tail?.next = rightNodes
    }
    
    var list = LinkedList<T>() // create new list
    list.head = newHead // set head to new head
    list.tail = { // set tail, move tail to the end
        while let next = tail?.next {
            tail = next
        }
        return tail
    }()
    
    return list // return the new list
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章