package top100liked import ( "fmt" "testing" ) // https://leetcode.cn/problems/swap-nodes-in-pairs/description/?envType=study-plan-v2&envId=top-100-liked type ListNode struct { Val int Next *ListNode } func swapPairs(head *ListNode) *ListNode { if head == nil { return nil } if head.Next == nil { return head } dummy := &ListNode{0, head} p1, p2, p3 := dummy, dummy.Next, dummy.Next.Next for { p1.Next = p3 p2.Next = p3.Next p3.Next = p2 p2, p3 = p3, p2 for range 2 { if p3.Next == nil { return dummy.Next } p1 = p1.Next p2 = p2.Next p3 = p3.Next } } } // func swapPairs(head *ListNode) *ListNode { // dummyHead := &ListNode{0, head} // temp := dummyHead // for temp.Next != nil && temp.Next.Next != nil { // node1 := temp.Next // node2 := temp.Next.Next // temp.Next = node2 // node1.Next = node2.Next // node2.Next = node1 // temp = node1 // } // return dummyHead.Next // } func Test(t *testing.T) { input1 := &ListNode{ Val: 1, Next: &ListNode{ Val: 2, Next: &ListNode{ Val: 3, Next: &ListNode{ Val: 4, Next: nil, }, }, }, } input2 := &ListNode{ Val: 1, Next: &ListNode{ Val: 2, Next: &ListNode{ Val: 3, Next: nil, }, }, } output := swapPairs(input1) for output != nil { fmt.Print(output.Val, " ") output = output.Next } fmt.Println() output = swapPairs(input2) for output != nil { fmt.Print(output.Val, " ") output = output.Next } }