-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rotate_List.java
56 lines (50 loc) · 1.2 KB
/
Rotate_List.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
package com.leet_code;
import com.LinkedList.LL;
public class Rotate_List {
Node head;
public static class Node {
private int val;
private Node next;
public Node(){}
public Node(int value){
this.val=value;
}
public Node(int value, Node next){
this.val=value;
this.next= next;}
}
public void insertfirst(int val){
Node node=new Node(val);
node.next=head;
head = node ;
}
public void display(){
Node temp=head;
while (temp!= null){
System.out.print(temp.val+" -> ");
temp=temp.next;
}
System.out.println("end");
}
public Node rotateRight(Node head, int k) {
if (k==0 || head== null||head.next==null) {
return head;
}
Node last =head;
int length=1;
while (last.next!=null){
last=last.next;
length++;
}
last.next=head;
int rotation=k;
int skip=length-rotation;
Node newlast = head;
for (int i = 0; i < skip-1; i++) {
newlast = newlast.next;
}
head=newlast.next;
newlast.next=null;
return head;
}
}