In fact your doubly linked list should have the following variables:
- int size - it's size of your list, it allows you to return size with O(1) complexity
- Node head - it's link to head of your list (first Node)
- Node tail - it's link to tail of your list (last Node)
Previous and Next Nodes should be declared in class 'Node'. It means that every node will have link to previous and next node.
Here is small example, but it's better to use generics to make your list more flexible (then it could support different types, not only int):
public class DoublyLinkedList {
private int size;
private Node head;
private Node tail;
public void addFirst(int value) {
size++;
// already have head (list not empty)
if (head != null) {
// creating new "head" element, old "head" now has previous value
head.previous = new Node(null, value, head);
head = head.previous; // update head
return;
}
// empty list, so create first node
head = new Node(null, value, null);
tail = head; // because we have only one element, and it also becomes tail
}
public void add(int value) {
size++;
// already have tail (list not empty)
if (tail != null) {
tail.next = new Node(tail, value, null); // creating new "tail" node with given value, old "tail" now has next value
tail = tail.next; // update tail
return;
}
// empty list, so create first node
if (head == null) {
head = new Node(null, value, null);
tail = head; // because we have only one element, and it also becomes tail
}
}
public int getSize() {
return size;
}
private static class Node {
private Node previous;
private Node next;
private int data;
public Node(Node previous, int data, Node next) {
this.previous = previous;
this.data = data;
this.next = next;
}
}
}