欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Swap Nodes in Pairs

程序员文章站 2022-03-05 08:09:47
...

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
}

转载于:https://www.jianshu.com/p/02fd9247d0b8