Swift Mege Sort

5 篇文章 0 订阅
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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值