-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path025.rb
More file actions
40 lines (37 loc) · 784 Bytes
/
025.rb
File metadata and controls
40 lines (37 loc) · 784 Bytes
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
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val)
# @val = val
# @next = nil
# end
# end
# @param {ListNode} head
# @param {Integer} k
# @return {ListNode}
def reverse_k_group(head, k)
return head if head.nil?
return head if k == 1
result = head
current = head
while true do
return head if current.nil?
temp = k
current_k = current
values = []
while temp > 0 do
values.push(current_k.val)
current_k = current_k.next
break if current_k.nil?
temp -= 1
end
return head if values.length < k
values.reverse!
temp = k
while temp > 0 do
current.val = values.shift
current = current.next
temp -= 1
end
end
end