Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.0 kB
3
Indexable
Never
func mergeTwoLists(_ list1: ListNode?, _ list2: ListNode?) -> ListNode? {

        var firstList: ListNode? = list1
        var secondList: ListNode? = list2
        var finalList: ListNode? = ListNode(0, nil)
        var tmpListNode: ListNode? = finalList
        
        while(firstList != nil && secondList != nil) {
            if firstList!.val <= secondList!.val {
                tmpListNode!.next = firstList
                tmpListNode = firstList
                firstList = firstList!.next
            }else {
                tmpListNode!.next = secondList
                tmpListNode = secondList
                secondList = secondList!.next
            }
        }
        while(firstList != nil) {
            tmpListNode!.next = firstList
            tmpListNode = firstList
            firstList = firstList!.next
        }
        while(secondList != nil) {
            tmpListNode!.next = secondList
            tmpListNode = secondList
            secondList = secondList!.next
        }
        return finalList!.next
    }