原题
https://leetcode.cn/problems/reverse-linked-list-ii/description
题解
头插法
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseBetween(head *ListNode, left int, right int) *ListNode {
empty := &ListNode{}
empty.Next = head
cur := empty // 代表当前遍历节点
i := 0
var intervalLeft *ListNode // 代表要插入位置的前一个节点
var prev *ListNode // 代表当前遍历节点的前一个节点
for cur != nil{
temp := cur.Next
if i == left - 1 {
intervalLeft = cur
}
// 需要插入的情况,prev不变,cur仍往后遍历
if i > left && i <= right{
origin := intervalLeft.Next
intervalLeft.Next = cur
prev.Next = temp
cur.Next = origin
} else{
prev = cur
}
cur = temp
i++
}
return empty.Next
}
原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode92-%e5%8f%8d%e8%bd%ac%e9%93%be%e8%a1%a8/