Swap Nodes in Pairs


#1

Given a linked list, swap every two adjacent nodes and return its head.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

Note:

  • Your algorithm should use only constant extra space.
  • You may not modify the values in the list's nodes, only nodes itself may be changed.

#2

Solution in Golang using two pointers,

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func swapPairs(head *ListNode) *ListNode {
    dh := &ListNode{Val : 0, Next : head}
    cur := dh
    
    for cur.Next != nil && cur.Next.Next!=nil{
        n1 := cur.Next
        n2 := cur.Next.Next
        
        n1.Next = n2.Next
        cur.Next = n2
        cur.Next.Next = n1
        
        cur = cur.Next.Next
    }
    
    return dh.Next
}