24.两两交换链表中的节点
24.两两交换链表中的节点
题解
两种解法,第一种递归第二种迭代,链表题建议画图做
代码
package main
type ListNode struct {
Val int
Next *ListNode
}
func swapPairs1(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
newHead := head.Next
newHeadNext := newHead.Next
newHead.Next = head
head.Next = swapPairs1(newHeadNext)
return newHead
}
func swapPairs2(head *ListNode) *ListNode {
dummy := &ListNode{0, head}
cnt := dummy
for cnt.Next != nil && cnt.Next.Next != nil {
node1 := cnt.Next
node2 := cnt.Next.Next
cnt.Next = node2
node1.Next = node2.Next
node2.Next = node1
cnt = node1
}
return dummy.Next
}