Skip to main content

92. Reverse Linked List II

分析

建立在另一道题目的基础上来完成

206. Reverse Linked List Pasted image 20220421230449.png

题解

/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseBetween(head *ListNode, left int, right int) *ListNode {
var pre, after, start, end *ListNode
p := head
cnt := 0
for p != nil {
cnt++
if cnt + 1 == left {
pre = p
}
if cnt == left {
start = p
}
if cnt == right {
end = p
}
if cnt - 1 == right {
after = p
}

p = p.Next
}
end.Next = nil
reverse(start)
if pre != nil {
pre.Next = end
}
start.Next = after

if pre == nil {
return end
}
return head
}


// 1 -> 2 -> 3
func reverse(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
last := reverse(head.Next)
head.Next.Next = head
head.Next = nil
return last
}