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
上一篇: Slf4j LogBack
下一篇: Logback设置日志级别