-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
55 lines (53 loc) · 1.03 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package des1
import (
. "leetcode/leetcode/pkg/helper"
)
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseBetween(head *ListNode, left int, right int) *ListNode {
if left > right {
panic("left must be less than right")
}
if left == right {
return head
}
node := head
var prev, beforeFirstSub, firstSub *ListNode
i := 1
for node != nil {
next := node.Next
if i >= left && i <= right {
node.Next = prev
prev = node
if i == left {
firstSub = node
}
if i == right {
if beforeFirstSub != nil { // subsequence is not at the beginning
beforeFirstSub.Next.Next = next
beforeFirstSub.Next = node
break
}
if next == nil { //subsequence is the whole list
head = node
break
}
// subsequence is at the beginning of the list and does not include the whole element
head = node
firstSub.Next = next
break
}
}
if i == left-1 {
beforeFirstSub = node
}
node = next
i++
}
return head
}