-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathreverse_in_groups.rb
More file actions
41 lines (34 loc) · 863 Bytes
/
reverse_in_groups.rb
File metadata and controls
41 lines (34 loc) · 863 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
41
require_relative './linklist'
def reverse_in_groups(head, k)
return if head.nil?
current = head
prev = nil
nxt = nil
# if number of nodes is not a multiple of k
# left-out nodes, in the end, should remain as it is.
tmp = head
1.upto(k) do |i|
tmp = tmp.next
if tmp.nil? && i < k
puts i
return head
end
end
# Reverse first k nodes of the linked list
1.upto(k) do
nxt = current.next
current.next = prev
prev = current
current = nxt
end
# next is now a pointer to (k+1)th node
# recursively call for the list starting from current.
# And make rest of the list as next of first node
head.next = reverse_in_groups(nxt, k) unless nxt.nil?
# prev is new head of the input list
prev
end
ll = LinkList.new
1.upto(10).each { |i| ll.add(i) }
ll.head = reverse_in_groups(ll.head, 3)
ll.print