Linked list - Reverse without recursion - java
public class Reverse {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(4);
Node n5 = new Node(5);
Node n6 = new Node(6);
n1.setNext(n2);
n2.setNext(n3);
n3.setNext(n4);
n4.setNext(n5);
n5.setNext(n6);
n6.setNext(null);
Node nth = reverse(n1);
System.out.println(nth.getData());
}
private static Node reverse(Node head){
Node temp = null;
Node nextNode = null;
while(head != null){
nextNode = head.getNext();
head.setNext(temp);
temp = head;
head = nextNode;
}
return temp;
}
}
-----------------------------------------------
o/p:
6
Comments
Post a Comment