I recently submitted an implementation of a singly linked list and tried to apply some of the suggestions on this implementation. I decided not to implement the List interface as I only wanted to practice what I believed to be the most important methods. I'm wondering how I could tidy this up some more and improve upon it.
Singly Linked List: Java Singly Linked List Implementation
DoublyLinkedList.java
public class DoublyLinkedList<T> {
private class Node {
private T data;
Node next, prev;
public Node() {
}
public Node(T data) {
this.data = data;
}
}
private Node head, last;
private int size;
public DoublyLinkedList() {
this.size = 0;
}
public void addToBeginning(T data) {
Node temp = new Node(data);
if (head == null) {
head = temp;
last = head;
} else {
temp.next = head;
head.prev = temp;
head = temp;
}
size++;
}
public void add(T data) {
Node temp = new Node(data);
if (head == null) {
head = temp;
last = head;
} else {
last.next = temp;
temp.prev = last;
last = temp;
}
size++;
}
public void add(T data, int index) {
Node temp = new Node(data);
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException();
} else if (index == 0) {
addToBeginning(data);
} else if (index == size) {
add(data);
} else {
Node current = head;
for (int i = 0; i < index; i++) {
current = current.next;
}
Node previous = current.prev;
previous.next = temp;
temp.prev = previous;
temp.next = current;
current.prev = temp;
size++;
}
}
public T get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
} else {
Node current = head;
for (int i = 0; i < index; i++) {
current = current.next;
}
return current.data;
}
}
public void delete(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
} else if (index == 0) {
head = head.next;
head.prev = null;
size--;
} else if (index == size - 1) {
last = last.prev;
last.next = null;
size--;
} else {
Node current = head;
for (int i = 0; i < index; i++) {
current = current.next;
}
Node previous = current.prev;
Node next = current.next;
previous.next = current.next;
next.prev = previous;
size--;
}
}
public int getSize() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
}