
需要在设置一个前置节点,来不停的移动
package mainimport "fmt"type ListNode struct {Val intNext *ListNode}func swapPairs1(head *ListNode) *ListNode {dummy := &ListNode{-1, nil}dummy.Next = headpreNode := dummy // 就是前一个节点for head != nil && head.Next!= nil{first := headsecond := head.Next//交换前两个节点first.Next = second.Nextsecond.Next = firstpreNode.Next =secondpreNode = first //需要把位置移到前一个节点去head = first.Next}return dummy.Next}func swapPairs(head *ListNode) *ListNode {dummy := &ListNode{}dummy.Next = headpreNode := dummyfor head!=nil&&head.Next!=nil{first := headsecond := head.Next// 交换数据preNode.Next = secondfirst.Next = second.Nextsecond.Next = first// 移动preNode = firsthead = first.Next}return dummy.Next}func main() {a := &ListNode{Val: 1}b := &ListNode{Val: 2}c := &ListNode{Val: 3}d := &ListNode{Val: 4}e := &ListNode{Val: 5}f := &ListNode{Val: 6}a.Next=bb.Next =cc.Next = dd.Next = ee.Next = fh := swapPairs1(a)for h!=nil{fmt.Println(h.Val)h=h.Next}}
递归
func swapPairs2(head *ListNode) *ListNode {//终止条件:链表只剩一个节点或者没节点了,没得交换了。返回的是已经处理好的链表if head ==nil||head.Next==nil {return head}//一共三个节点:head, next, swapPairs(next.next)//下面的任务便是交换这3个节点中的前两个节点next := head.Nexthead.Next= swapPairs2(next.Next)next.Next = head//根据第二步:返回给上一级的是当前已经完成交换后,即处理好了的链表部分return next}


