-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathreverse_in_group_iterative.rb
90 lines (75 loc) · 1.64 KB
/
reverse_in_group_iterative.rb
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
89
90
require_relative './linklist'
def reverse_in_groups(head, k)
return if head.nil?
reversed_ll = LinkList.new
current = head
prev = nil
until current.nil?
ll = LinkList.new
count = 0
head = current
while count < k && current
ll.head = insert_at_begining(ll.head, current.val)
current = current.next
if count.zero?
tail = prev
prev = ll.head
end
count += 1
end
reversed_ll.head = ll.head if reversed_ll.head.nil?
if count < k
tail.next = head
elsif tail
tail.next = ll.head
end
end
# puts reversed_ll.head
reversed_ll.head
end
def reverse_k_group(head, k)
return if head.nil?
reversed_ll = nil
current = head
prev = nil
until current.nil?
group_ll = nil
count = 0
head = current
while count < k && current
group_ll = insert_at_begining(group_ll, current.val)
current = current.next
# First element of the loop will be become tail of group ll
if count.zero?
tail = prev
prev = group_ll
end
count += 1
end
reversed_ll = group_ll if reversed_ll.nil?
# If there were no sufficient elements in the group
# then append leftover orignal list
if count < k
tail.next = head
elsif tail
tail.next = group_ll
end
end
reversed_ll
end
def insert_at_begining(head, val)
node = Node.new(val)
return node if head.nil?
node.next = head
node
end
def remove_first(head)
return if head.nil?
node = head
head = node.next
[node, head]
end
ll = LinkList.new
1.upto(11).each { |i| ll.add(i) }
ll.head = reverse_k_group(ll.head, 3)
ll.print