-
Notifications
You must be signed in to change notification settings - Fork 187
/
RotateLinkedList.java
65 lines (57 loc) · 1.03 KB
/
RotateLinkedList.java
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
class LinkedList {
Node head;
class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
void rotate(int k)
{
if (k == 0)
return;
Node current = head;
int count = 1;
while (count < k && current != null) {
current = current.next;
count++;
}
if (current == null)
return;
Node kthNode = current;
while (current.next != null)
current = current.next;
current.next = head;
head = kthNode.next;
kthNode.next = null;
}
void push(int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
void printList()
{
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public static void main(String args[])
{
LinkedList llist = new LinkedList();
for (int i = 60; i >= 10; i -= 10)
llist.push(i);
System.out.println("Given list");
llist.printList();
llist.rotate(4);
System.out.println("Rotated Linked List");
llist.printList();
}
}