Swap Nodes in Pairs

Problem - Swap Nodes in Pairs

Solution 1(in Go) - Swap the two nodes by Next link

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func swapPairs(head *ListNode) *ListNode {
    if head == nil || head.Next == nil {
        return head
    }
    
    newHead := head.Next
    head.Next = swapPairs(newHead.Next)
    newHead.Next = head
    
    return newHead
}

Solution 2(in Go) - Only swap the Val of two nodes

func swapPairs(head *ListNode) *ListNode {
    if head == nil || head.Next == nil {
        return head
    }
    
    head.Val, head.Next.Val = head.Next.Val, head.Val
    swapPairs(head.Next.Next)

    return head
}

你可能感兴趣的:(Swap Nodes in Pairs)