mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-13 14:10:38 +08:00
添加 24. 两两交换链表中的节点 Swift版本
This commit is contained in:
@ -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
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
|
Reference in New Issue
Block a user