92. 反转链表 II

92. 反转链表 II #

题目地址 #

解题思路 #

具体实现 #

package main

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

func reverseBetween(head *ListNode, left int, right int) *ListNode {
	if head == nil {
		return head
	}

	var (
		dummy      = &ListNode{}
		prev, curr *ListNode
	)
	dummy.Next = head
	prev = dummy

	for i := 0; i < left-1; i++ {
		prev = prev.Next
	}

	curr = prev.Next
	for i := 0; i < right-left; i++ {
		next := curr.Next
		curr.Next = curr.Next.Next
		next.Next = prev.Next
		prev.Next = next
	}

	return dummy.Next
}

func main() {
	ret := reverseBetween(&ListNode{
		Val: 1,
		Next: &ListNode{
			Val: 2,
			Next: &ListNode{
				Val: 3,
				Next: &ListNode{
					Val: 4,
					Next: &ListNode{
						Val:  5,
						Next: nil,
					},
				},
			},
		},
	}, 2, 4)

	fmt.Println(ret)
}

参考 #