题目
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 示例 1:
输入:head = [1,2,3,4]输出:[2,1,4,3]示例 2:输入:head = []输出:[]示例 3:输入:head = [1]输出:[1] 提示:链表中节点的数目在范围 [0, 100] 内0 <= Node.val <= 100
解题思路
代码语言:javascript复制/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init() { self.val = 0; self.next = nil; }
* public init(_ val: Int) { self.val = val; self.next = nil; }
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/
class Solution {
func swapPairs(_ head: ListNode?) -> ListNode? {
guard let head = head, let next = head.next else {
return head
}
let dummy = ListNode(-1, head)
var prev: ListNode? = dummy
var cur: ListNode? = prev?.next
while cur != nil && cur?.next != nil {
let nextNode = cur?.next
cur?.next = nextNode?.next
nextNode?.next = cur
prev?.next = nextNode
prev = cur
cur = cur?.next
}
return dummy.next
}
}