Program: Reverse a singlylinked List
complexity : O(n)
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package careercup.google;
/**
*
* @author Harit
*/
public class SinglyLinkedListNode {
private int value;
private int next;
public SinglyLinkedListNode(int v){
this.value = v;
this.next = -1;
}
public int getValue(){
return this.value;
}
public int getNext(){
return this.next;
}
public void setNext(int n){
this.next = n;
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package careercup.google;
/**
*
* @author Harit
*/
public class ReverseSinglyLinkedList {
private static int[] input = new int[]{0,1,2,3,4,5,6,7};
private static SinglyLinkedListNode[] nodes = new SinglyLinkedListNode[input.length];
private static int head = -1;
private static int tail = -1;
public static void main(String args[]){
createList();
printList(head);
printList(reverseList(head));
}
private static void createList(){
for(int i=0; i<input.length; i++){
SinglyLinkedListNode node = new SinglyLinkedListNode(input[i]);
nodes[i] = node;
if(i==0){
head = i;
tail = i;
continue;
}
/* setting parent's next*/
nodes[i-1].setNext(i);
tail = i;
}
}
private static int reverseList(int head){
SinglyLinkedListNode next = null;
SinglyLinkedListNode current = null;
int result = -1;
current = nodes[head];
while(current != null){
if(current.getNext() == -1){
current.setNext(result);
result = current.getValue();
break;
}
next = nodes[current.getNext()];
current.setNext(result);
result = current.getValue();
current = next;
}
return result;
}
private static void printList(int head){
while(head != -1){
System.out.print(nodes[head].getValue() + " ");
head = nodes[head].getNext();
}
System.out.println("");
}
}
Output:
run: 0 1 2 3 4 5 6 7 7 6 5 4 3 2 1 0 BUILD SUCCESSFUL (total time: 0 seconds)
