Swap Nodes in Pairs

Solution in Go

func swapPairs(head *ListNode) *ListNode {
    dummy := &ListNode{Next: head}
    prev := dummy
    curr := head

    for curr != nil && curr.Next != nil {
        next := curr.Next
        curr.Next = curr.Next.Next
        prev.Next = next
        next.Next = curr
        prev = curr
        curr = curr.Next
    }

    return dummy.Next
}
Subscribe via email

Get notified once/twice per month when new articles are published.

Copyright © 2022 - 2024 TheDeveloperCafe.
The Go gopher was designed by Renee French.