-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverse-linked-list-ii.go
88 lines (80 loc) · 1.53 KB
/
reverse-linked-list-ii.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"fmt"
"bytes"
)
type ListNode struct {
Val int
Next *ListNode
}
func (n *ListNode) String() string {
var buf bytes.Buffer
for nn := n; nn != nil; nn = nn.Next {
buf.WriteString(fmt.Sprintf("[%d]", nn.Val))
}
return buf.String()
}
func reverseBetween(head *ListNode, m int, n int) *ListNode {
if head == nil || head.Next == nil || m <= 0 || n <= 0 || m >= n {
return head
}
mNode, nNode := findSubList(head, m, n)
if mNode == nil || nNode == nil || mNode == nNode {
return head
}
nextSubNode := nNode.Next
h, t := doReverse(mNode, nNode)
t.Next = nextSubNode
if t == head {
return h
}
for n := head; n != nil; n = n.Next {
if n.Next == t {
n.Next = h
break
}
}
return head
}
func doReverse(head, tail *ListNode) (*ListNode, *ListNode) {
if head == nil || tail == nil || head == tail {
return tail, head
}
pre, cur, next := head, head.Next, head.Next.Next
for {
cur.Next = pre
if cur == tail {
break
}
pre = cur
cur = next
next = next.Next
}
head.Next = nil
return tail, head
}
func findSubList(head *ListNode, m, n int) (mNode, nNode *ListNode) {
if head == nil {
return nil, nil
}
mNode, nNode = head, head
for i := 1; i < n; i++ {
if i < m {
mNode = mNode.Next
if mNode == nil {
return
}
}
nNode = nNode.Next
if nNode == nil {
return
}
}
return
}
func main() {
h := &ListNode{1, &ListNode{2, &ListNode{3, &ListNode{4, &ListNode{5, nil}}}}}
//h := &ListNode{3, &ListNode{5, nil}}
fmt.Println(h)
fmt.Println(reverseBetween(h, 3, 4))
}