-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathRotate_a_Linked_List.java
More file actions
72 lines (60 loc) · 1.52 KB
/
Rotate_a_Linked_List.java
File metadata and controls
72 lines (60 loc) · 1.52 KB
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
// { Driver Code Starts
import java.util.*;
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int a = sc.nextInt();
Node head = new Node(a);
Node tail = head;
for (int i=0; i<n-1; i++)
{
a = sc.nextInt();
tail.next = new Node(a);
tail = tail.next;
}
int k = sc.nextInt();
Rotate g = new Rotate();
head = g.rotate(head,k);
printList(head);
}
}
public static void printList(Node n) {
while (n != null) {
System.out.print(n.data + " ");
n = n.next;
}
System.out.println();
}
}
class Rotate{
public Node rotate(Node head, int k) {
Node curr = head;
int count = 1;
while( curr != null && count < k ){
curr = curr.next;
count++;
}
if(curr == null ){
return head;
}
Node kthnode = curr;
while( curr.next != null ){
curr = curr.next;
}
curr.next = head;
head = kthnode.next;
kthnode.next = null;
return head;
}
}