Skip to content

Commit edd3ed2

Browse files
author
Yeqi Tao
committed
Add Soulution.go for 0025.Reverse Nodes in k-Group
1 parent 3316874 commit edd3ed2

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* type ListNode struct {
4+
* Val int
5+
* Next *ListNode
6+
* }
7+
*/
8+
func reverseKGroup(head *ListNode, k int) *ListNode {
9+
start := head
10+
var h *ListNode = nil
11+
var t *ListNode = nil
12+
ok := false
13+
if h, t, ok = revert(start, k); !ok {
14+
return head
15+
}
16+
r := h
17+
p := t
18+
print(2, r)
19+
for ok {
20+
start = t.Next
21+
h, t, ok = revert(start, k)
22+
p.Next = h
23+
p = t
24+
}
25+
return r
26+
}
27+
28+
func revert(head *ListNode, k int) (h, t *ListNode, ok bool) {
29+
c := head
30+
if !check(c, k) {
31+
return head, nil, false
32+
}
33+
34+
t = head
35+
var p *ListNode = nil
36+
for k > 0 {
37+
temp := head
38+
head = head.Next
39+
temp.Next = p
40+
p = temp
41+
k--
42+
}
43+
h = p
44+
t.Next = head
45+
ok = true
46+
print(11, h)
47+
return
48+
}
49+
50+
func check(head *ListNode, k int) bool {
51+
for k > 0 {
52+
if head == nil {
53+
return false
54+
}
55+
k--
56+
head = head.Next
57+
}
58+
return true
59+
}

0 commit comments

Comments
 (0)