This code works just fine as I get the correct output. However I want to make my code more simple. I want to avoid using the setPrev(Node n)
method and would rather set the reference to the previous node in the Node(String s)
constructor directly somehow. I mainly want to know if this is the 'right' way to implement a Doubly linked list though.
public class DoublyLinkedList {
private Node current;
private Node first;
private Node traverse;
private int count = 0;
public DoublyLinkedList(String s)
{
first = new Node(s);
current = first;
}
public void add(String s){
current.next = new Node(s);
current.next.setPrev(current);
current = current.next;
}
public void traverseForward(){
count++;
if(count==1)
traverse = first;
else
traverse = traverse.next;
System.out.println(traverse.toString());
}
public void traverseBackward(){
count--;
if(count < 1)
traverse = null;
else if(count == 1)
traverse = first;
else
traverse = traverse.prev;
System.out.println(traverse.toString());
}
private class Node{
private Node next;
private Node prev;
private String name;
public Node(String s)
{
this.name = s;
this.next = null;
}
public void setPrev(Node n){
this.prev = n;
}
public String toString(){
return this.name;
}
}
}