2022-06-28
Description
Input: head = [1,2,3,4]
Output: [2,1,4,3]Input: head = []
Output: []Input: head = [1]
Output: [1]Solution
Approach #0
Last updated
Input: head = [1,2,3,4]
Output: [2,1,4,3]Input: head = []
Output: []Input: head = [1]
Output: [1]Last updated
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func swapPairs(head *ListNode) *ListNode {
cur := head
for cur != nil && cur.Next != nil {
next := cur.Next
cur.Val, next.Val = next.Val, cur.Val
cur = next.Next
}
return head
}