Rotate LinkedList - Java
public class LLNode {
private LLNode next;
private Object value;
public LLNode getNext() {
return next;
}
public LLNode setNext(LLNode next) {
this.next = next;
return this;
}
public Object getValue() {
return value;
}
public LLNode setValue(Object value) {
this.value = value;
return this;
}
}
public class Rotate {
public static LLNode getRotated(LLNode root, int rotatePosition){
LLNode current = null;
LLNode newStart;
if(root != null){
current = root;
}
for (int i = 0; i < rotatePosition - 1; i++) {
current = current.getNext();
}
newStart = current.getNext();
current.setNext(null);
current = newStart;
while (current.getNext() != null)
current = current.getNext();
current.setNext(root);
return newStart;
}
public static void main(String[] args) {
LLNode n1 = new LLNode();
LLNode n2 = new LLNode();
LLNode n3 = new LLNode();
LLNode n4 = new LLNode();
LLNode n5 = new LLNode();
LLNode n6 = new LLNode();
n1.setNext(n2).setValue(1);
n2.setNext(n3).setValue(2);
n3.setNext(n4).setValue(3);
n4.setNext(n5).setValue(4);
n5.setNext(n6).setValue(5);
n6.setNext(null).setValue(6);
LLNode rotated = getRotated(n1,2);
while(rotated.getNext() != null){
System.out.println(rotated.getValue());
rotated = rotated.getNext();
}
System.out.println(rotated.getValue());
}
}
Output:
3
4
5
6
1
2
private LLNode next;
private Object value;
public LLNode getNext() {
return next;
}
public LLNode setNext(LLNode next) {
this.next = next;
return this;
}
public Object getValue() {
return value;
}
public LLNode setValue(Object value) {
this.value = value;
return this;
}
}
public class Rotate {
public static LLNode getRotated(LLNode root, int rotatePosition){
LLNode current = null;
LLNode newStart;
if(root != null){
current = root;
}
for (int i = 0; i < rotatePosition - 1; i++) {
current = current.getNext();
}
newStart = current.getNext();
current.setNext(null);
current = newStart;
while (current.getNext() != null)
current = current.getNext();
current.setNext(root);
return newStart;
}
public static void main(String[] args) {
LLNode n1 = new LLNode();
LLNode n2 = new LLNode();
LLNode n3 = new LLNode();
LLNode n4 = new LLNode();
LLNode n5 = new LLNode();
LLNode n6 = new LLNode();
n1.setNext(n2).setValue(1);
n2.setNext(n3).setValue(2);
n3.setNext(n4).setValue(3);
n4.setNext(n5).setValue(4);
n5.setNext(n6).setValue(5);
n6.setNext(null).setValue(6);
LLNode rotated = getRotated(n1,2);
while(rotated.getNext() != null){
System.out.println(rotated.getValue());
rotated = rotated.getNext();
}
System.out.println(rotated.getValue());
}
}
Output:
3
4
5
6
1
2
Comments
Post a Comment