Skip to content

Instantly share code, notes, and snippets.

@skdangi
Last active December 28, 2015 04:49
Show Gist options
  • Save skdangi/7444855 to your computer and use it in GitHub Desktop.
Save skdangi/7444855 to your computer and use it in GitHub Desktop.
Reverse a list by k slots
public class ReverseKList {
public static class Node{
Node next;
int value;
public Node(int value){
this.value = value;
}
@Override
public String toString() {
return value+" -->"+(next==null?"":next.value);
}
}
public static Node reverseK(Node node, int k){
Node start= node;
Node end = node;
Node temp;
Node prevListEnd=null;
int count =0;
boolean headUpdated = false;
while(end!=null){
end = end.next;
count++;
if(count == k){
temp = reverse(start, end);
if(prevListEnd!=null){
prevListEnd.next = temp;
}
if(!headUpdated){
node = temp;
headUpdated = true;
}
prevListEnd= start;
start = end;
count=0;
}
}
if(prevListEnd!=null){
prevListEnd.next = start;
}
return node;
}
public static void print(Node node){
while(node !=null){
System.out.println(node.value);
node = node.next;
}
}
public static Node reverse(Node start, Node end){
if(start==null||start.next==null){
return start;
}
Node prev = start;
Node succ = start.next;
Node temp;
while(succ!=end){
temp = succ.next;
succ.next = prev;
prev = succ;
succ = temp;
}
return prev;
}
public static void main(String[] args) {
Node node1= new Node(1);
Node node2= new Node(2);
Node node3= new Node(3);
Node node4= new Node(4);
Node node5= new Node(5);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
print(node1);
print(reverseK(node1, 2));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment