題目連結: https://leetcode.com/problems/swap-nodes-in-pairs/
//Time complexity: O(n)
func swapPairs(_ head: ListNode?) -> ListNode? {
guard let head = head else { return nil }
if head.next == nil { return head }
var newHead, ptr1, ptr2, ptr3, ptr4: ListNode?
ptr1 = nil
ptr2 = head
ptr3 = head.next
newHead = ptr3
ptr4 = head.next?.next
while ptr2 != nil && ptr3 != nil {
ptr3?.next = ptr2
ptr2?.next = ptr4
ptr1?.next = ptr3
ptr1 = ptr2
ptr2 = ptr4
ptr3 = ptr4?.next
ptr4 = ptr4?.next?.next
}
return newHead
}