添加 24. 两两交换链表中的节点 Swift版本

This commit is contained in:
极客学伟
2021-08-19 16:33:56 +08:00
parent 391a04bf9f
commit b3ac4e3b2a

View File

@ -248,6 +248,27 @@ fun swapPairs(head: ListNode?): ListNode? {
}
```
Swift:
```swift
func swapPairs(_ head: ListNode?) -> ListNode? {
if head == nil || head?.next == nil {
return head
}
let dummyHead: ListNode = ListNode(-1, head)
var current: ListNode? = dummyHead
while current?.next != nil && current?.next?.next != nil {
let temp1 = current?.next
let temp2 = current?.next?.next?.next
current?.next = current?.next?.next
current?.next?.next = temp1
current?.next?.next?.next = temp2
current = current?.next?.next
}
return dummyHead.next
}
```
-----------------------