Skip to content

Commit 082a46b

Browse files
Merge pull request #89 from hemabhagnani/hemabhagnani
added Clockwise Rotation in linked list
2 parents 236b393 + be8dc36 commit 082a46b

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

Linked Lists/ClockwiseRotation.java

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
2+
class ClockwiseRotation
3+
{
4+
//node of linked_list
5+
static class Node
6+
{
7+
int data;
8+
Node next;
9+
}
10+
11+
//insert data into list
12+
static Node push(Node head_ref, int new_data)
13+
{
14+
Node new_node = new Node();
15+
new_node.data = new_data;
16+
new_node.next = (head_ref);
17+
(head_ref) = new_node;
18+
return head_ref;
19+
}
20+
21+
//print the linked_list
22+
static void printList(Node node)
23+
{
24+
while (node != null)
25+
{
26+
System.out.print(node.data + " -> ");
27+
node = node.next;
28+
}
29+
System.out.println( "null");
30+
}
31+
32+
33+
static Node clockwise_rotate(Node head, int k)
34+
{
35+
if (head == null)
36+
return head;
37+
38+
Node tmp = head;
39+
int len = 1;
40+
while (tmp.next != null)
41+
{
42+
tmp = tmp.next;
43+
len++;
44+
}
45+
46+
if (k > len)
47+
k = k % len;
48+
49+
k = len - k;
50+
if (k == 0 || k == len)
51+
return head;
52+
53+
Node current = head;
54+
int cnt = 1;
55+
while (cnt < k && current != null)
56+
{
57+
current = current.next;
58+
cnt++;
59+
}
60+
61+
if (current == null)
62+
return head;
63+
Node kthnode = current;
64+
tmp.next = head;
65+
head = kthnode.next;
66+
kthnode.next = null;
67+
return head;
68+
69+
}
70+
71+
public static void main(String args[])
72+
{
73+
Node head = null;
74+
head = push(head, 5);
75+
head = push(head, 4);
76+
head = push(head, 3);
77+
head = push(head, 2);
78+
head = push(head, 1);
79+
printList(head);
80+
int k = 2;
81+
System.out.println("k="+k);
82+
Node updated_head = clockwise_rotate(head, k);
83+
System.out.println("rotated list");
84+
printList(updated_head);
85+
}
86+
}

0 commit comments

Comments
 (0)