tmp := cur.Next // 暂存 cur 的 next 节点 cur.Next = pre // 将 pre 节点赋值给 cur.Next pre = cur // pre向后移动一步 cur = tmp // cur向后移动一步
可以把上面的步骤合并成一句,完整代码如下:
1 2 3 4 5 6 7 8
funcreverseList(head *ListNode) *ListNode { var pre *ListNode cur := head for cur != nil { pre, cur, cur.Next = cur, cur.Next, pre } return pre }
定义 pre 节点的时候,用 var 关键字声明并初始化为零值,即 nil。如果用短变量声明操作符 := 做不到将 pre 设置为 nil。
2、递归解法
1 2 3 4 5 6 7 8 9
funcreverseList(head *ListNode) *ListNode { if head == nil || head.Next == nil { return head } last := reverseList(head.Next) head.Next.Next = head head.Next = nil return last }
funcreverseN(head *ListNode, n int) *ListNode { preHead := &ListNode{ Next: head, } var pre *ListNode cur := head i := 0 for i < n { pre, cur, cur.Next = cur, cur.Next, pre i++ } preHead.Next.Next = cur return pre }
2、递归解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
funcreverseN(head *ListNode, n int) *ListNode { var successor *ListNode // 用于记录第n个节点的next节点 var helper func(head *ListNode, n int) *ListNode helper = func(head *ListNode, n int) *ListNode { if n == 1 { successor = head.Next return head } last := helper(head.Next, n-1) head.Next.Next = head head.Next = successor return last } return helper(head, n) }
funcreverseBetween(head *ListNode, left int, right int) *ListNode { preHead := &ListNode{ Next: head, } pre, cur, next := preHead, head, head.Next i := 1 for { if i < left { pre, cur, next = cur, next, next.Next } elseif i >= left && i < right { cur, next, next.Next = next, next.Next, cur } else { pre.Next.Next = next // 当超过范围之后,将pre.Next节点next节点指向next pre.Next = cur // pre节点的next指向指向cur break } i++ }
funcreverseBetween(head *ListNode, left int, right int) *ListNode { if left == 1 { return reverseN(head, right) }
head.Next = reverseBetween(head.Next, left-1, right-1) return head }
funcreverseN(head *ListNode, n int) *ListNode { var successor *ListNode // 用于记录第n个节点的next节点 var helper func(head *ListNode, n int) *ListNode helper = func(head *ListNode, n int) *ListNode { if n == 1 { successor = head.Next return head } last := helper(head.Next, n-1) head.Next.Next = head head.Next = successor return last } return helper(head, n) }
funcreverseKGroup(head *ListNode, k int) *ListNode { preHead := &ListNode{Next: head} pre := preHead for head != nil { tail := pre for i := 0; i < k; i++ { tail = tail.Next if tail == nil { return preHead.Next } } next := tail.Next head, tail = reverse(head, tail) pre.Next = head tail.Next = next pre = tail head = tail.Next } return preHead.Next }
funcreverse(head, tail *ListNode)(*ListNode, *ListNode) { pre := tail.Next cur := head for pre != tail { next := cur.Next cur.Next = pre pre = cur cur = next } return tail, head }
// 反转[a, b)的节点,当b=nil时,即反转整个链表 funcreverse(a, b *ListNode) *ListNode { var pre *ListNode cur := a for cur != b { pre, cur, cur.Next = cur, cur.Next, pre } return pre }