# Rotate linked list clockwise by k nodes in ruby

Ruby program for Rotate linked list clockwise by k nodes. Here mentioned other language solution.

``````#  Ruby program for
#  Rotate a list by moving each element
#  k times to the right.
#  Or clockwise rotation of linked list

attr_accessor :data, :next
def initialize(data)
self.data = data
self.next = nil
end
end

class SingleLL
# Define the accessor and reader of class SingleLL
def initialize()
self.tail = nil
end

else
#  Append the node at last position
self.tail.next = node
end
self.tail = node
end

def display()
return
end

while (temp != nil)
print(" " + temp.data.to_s + " →")
#  Visit to next node
temp = temp.next
end
print(" NULL\n")
end

#  This are perform the linked list rotation
def rotation(k)
#  Define some auxiliary variable
count = 0
#  Count number of node in linked list
while (auxiliary != nil)
#  visit to next node
auxiliary = auxiliary.next
count += 1
end
if (count <= 1)
#  When have less than 2 nodes in linked list
return
end

#  Get actual rotation
count = k % count
if (count == 0)
#  When actual linked list are not affected
return
end

#  Find the rotational node
while (count > 1)
#  Visit to next node
auxiliary = auxiliary.next
count -= 1
end

#  Connecting the last node to first node of linked list
#  Set new last node
self.tail = auxiliary
#  Set that there is no node after of tail
self.tail.next = nil
end

#  Handles the request to perform rotation
#  k is indicate node rotation
def clockwiseRotation(k)
if (k <= 0)
#  When invalid given k
return
end
return
end

print(" Before rotate \n")
self.display()
print(" Given k : " + k.to_s, "\n")
#  Perform rotation
self.rotation(k)
print(" After rotate \n")
self.display()
print("\n\n")
end

end

def main()
sll1 = SingleLL.new()
sll2 = SingleLL.new()
#  1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → NULL
#  4 → 9 → 7 → 3 → 8 → 6 → -2 → NULL
#  Test case
sll1.clockwiseRotation(3)
sll2.clockwiseRotation(18)
end

main()``````

Output

`````` Before rotate
1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → NULL
Given k : 3
After rotate
4 → 5 → 6 → 7 → 8 → 1 → 2 → 3 → NULL

Before rotate
4 → 9 → 7 → 3 → 8 → 6 → -2 → NULL
Given k : 18
After rotate