Skip to content

Commit 1aa6982

Browse files
author
beyondyyh
committed
Add reverse-linked-list-ii
1 parent fed9e86 commit 1aa6982

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed

algorithms/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
|0069|[x 的平方根](https://leetcode-cn.com/problems/sqrtx/)|[go](./binarysearch/69.mySqrt.go)|S|
2525
|0071|[简化路径](https://leetcode-cn.com/problems/simplify-path/)|[go](./mystring/71.simplifyPath.go)|M|
2626
|0078|[子集](https://leetcode-cn.com/problems/subsets/)|[go](./myarray/78.subsets.go)|M|
27+
|0092|[子集反转链表 II](https://leetcode-cn.com/problems/reverse-linked-list-ii/)|[go](./linkedList/92.reverseBetween.go)|M|
2728
|0093|[复原IP地址](https://leetcode-cn.com/problems/restore-ip-addresses/submissions/)|[go](./mystring/93.restoreIpAddresses.go)|M|
2829
|0094|[二叉树的中序遍历](https://leetcode-cn.com/problems/binary-tree-inorder-traversal/)|[go](./tree/94.inorderTraversal.go)|M|
2930
|0101|[对称二叉树](https://leetcode-cn.com/problems/symmetric-tree/submissions/)|[go](./tree/101.isSymmetric.go)|S|
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package linkedList
2+
3+
import (
4+
_ "fmt"
5+
6+
_ "Leetcode/algorithms/kit"
7+
)
8+
9+
func reverseBetween(head *ListNode, m, n int) *ListNode {
10+
var dummy *ListNode = &ListNode{Val: 0}
11+
dummy.Next = head
12+
pre := dummy
13+
for i := 1; i < m; i++ {
14+
pre = pre.Next
15+
}
16+
17+
curr := pre.Next
18+
for i := m; i < n; i++ {
19+
next := curr.Next
20+
curr.Next = next.Next
21+
next.Next = pre.Next
22+
pre.Next = next
23+
24+
// fmt.Printf("m=%d %v\n", m, kit.List2Ints(dummy.Next))
25+
}
26+
return dummy.Next
27+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package linkedList
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
7+
"Leetcode/algorithms/kit"
8+
)
9+
10+
type (
11+
entry92 struct {
12+
name string
13+
input entry92input
14+
expected []int
15+
}
16+
entry92input struct {
17+
ints []int
18+
m int
19+
n int
20+
}
21+
)
22+
23+
// run: go test -v base.go 92.*
24+
func Test_reverseBetween(t *testing.T) {
25+
cases := []entry92{
26+
{
27+
name: "x1",
28+
input: entry92input{ints: []int{1, 2, 3, 4, 5}, m: 2, n: 4},
29+
expected: []int{1, 4, 3, 2, 5},
30+
},
31+
{
32+
name: "x2",
33+
input: entry92input{ints: []int{1, 2, 3, 4, 5}, m: 1, n: 5},
34+
expected: []int{5, 4, 3, 2, 1},
35+
},
36+
}
37+
38+
for _, tc := range cases {
39+
head := kit.Ints2List(tc.input.ints)
40+
output := kit.List2Ints(reverseBetween(head, tc.input.m, tc.input.n))
41+
if !reflect.DeepEqual(output, tc.expected) {
42+
t.Errorf("reverseBetween(%v, %d, %d)=%v, expected=%v", tc.input.ints, tc.input.m, tc.input.n, output, tc.expected)
43+
}
44+
}
45+
}

0 commit comments

Comments
 (0)