-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotateLinkedList.java
More file actions
62 lines (60 loc) · 1.42 KB
/
RotateLinkedList.java
File metadata and controls
62 lines (60 loc) · 1.42 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
package Codes;
import java.util.Scanner;
public class RotateLinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
static void append(int d) {
Node newnode = new Node(d);
if (head == null) {
head = newnode;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newnode;
}
}
static void display(){
Node temp=head;
while (temp!=null){
System.out.print(temp.data+"->");
temp=temp.next;
}
}
static void rotate(int k){
Node temp=head;
int num=1;
while (temp!=null && num<k) {
temp = temp.next;
num++;
}
Node knode=temp;
while (temp.next!=null){
temp=temp.next;
}
temp.next=head;
head=knode.next;
knode.next=null;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String input=sc.nextLine();
String[] arr=input.split(" ");
for (int i=0;i<arr.length;i++){
append(Integer.parseInt(arr[i]));
}
display();
System.out.println();
int k=sc.nextInt();
rotate(k);
display();
}
}