https://leetcode-cn.com/problems/swap-nodes-in-pairs
Swift
func swapPairs(_ head: ListNode?) -> ListNode? {
let top = ListNode(110)
top.next = head
var current: ListNode? = top
while current?.next?.next != nil {
let temp = current?.next?.next?.next
let node0 = current?.next
let node1 = current?.next?.next
node1?.next = node0
node0?.next = temp
current?.next = node1
current = current?.next?.next
}
return top.next
}
- 遍历的同时依次交换两个节点