Skip to content

Latest commit

 

History

History
executable file
·
34 lines (23 loc) · 642 Bytes

File metadata and controls

executable file
·
34 lines (23 loc) · 642 Bytes

24、两两交换链表中的节点

https://leetcode-cn.com/problems/swap-nodes-in-pairs

Solution

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
}

Tip

  • 遍历的同时依次交换两个节点