Problem in Reversing a linked list without using recursion.
I used this method, but when i try and run this back home, I am not able to print the reverse of the lin
class Node {
Node next;
int value;
public Node() {
}
public Node(Node next, int value) {
super();
this.next = next;
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
public class Linkedlist {
private Node head = null;
public Linkedlist(Node head) {
this.head = head;
}
public void iterate() {
Node current = head;
while (current != null) {
System.out.println(current.getValue());
current = current.getNext();
}
}
public void reverse() {
Node current = head;
Node prev = null;
while (current != null) {
Node temp = current.next;
current.next = prev;
prev = current;
current = temp;
}
head = prev;
}
public static void main(String[] args) {
Node n = new Node(null, 10);
Node n1 = new Node(n, 20);
Node n2 = new Node(n1, 30);
Node n3 = new Node(n2, 40);
Node n4 = new Node(n3, 50);
Node n5 = new Node(n4, 60);
Linkedlist linkedlist = new Linkedlist(n5);
linkedlist.iterate();
linkedlist.reverse();
System.out.println("------------------REVERSED---------------------");
linkedlist.iterate();
}
}