public class DoublyLinkedList {
private Node first;
private Node last;
public DoublyLinkedList() {
this.first = new Node();
this.last = new Node();
}
public void print() {
Node current = first;
while (current.next != null) {
current = current.next;
System.out.print(current.data + "\t");
}
System.out.println();
}
public void addAtHead(long data) {
Node node = new Node(data);
if (isEmpty()) {
first.next = node;
last.prev = node;
} else {
Node old = first.next;
node.next = old;
old.prev = node;
first.next = node;
}
}
public void addAtTail(long data) {
Node node = new Node(data);
if (isEmpty()) {
first.next = node;
last.prev = node;
} else {
Node old = last.prev;
node.prev = old;
old.next = node;
last.prev = node;
}
}
public long get(int index) {
if (index >= 0) {
int i = -1;
Node current = first;
while (current.next != null) {
i++;
if (i == index) {
return current.next.data;
}
current = current.next;
}
} else {
int i = 0;
Node current = last;
while (current.prev != null) {
i--;
if (i == index) {
return current.prev.data;
}
current = current.prev;
}
}
return -1;
}
public void reversePrint() {
Node current = last;
while (current.prev != null) {
current = current.prev;
System.out.print(current.data + "\t");
}
System.out.println();
}
private boolean isEmpty() {
return first.next == null;
}
public static void main(String[] args) {
DoublyLinkedList list = new DoublyLinkedList();
list.addAtHead(1L);
list.print();
list.addAtHead(0L);
list.print();
list.addAtTail(3L);
list.print();
System.out.println(list.get(0));
System.out.println(list.get(-1));
System.out.println(list.get(-2));
System.out.println(list.get(-3));
System.out.println(list.get(-4));
}
public void remove(int index) {
if (index < 0) {
throw new IllegalArgumentException("");
}
if (isEmpty()) {
return;
}
Node current = first;
int i = -1;
while (current.next != null) {
i++;
if (i == index) {
Node target = current.next;
if (target.next != null) {
target.next.prev = current;
} else {
last.prev = current;
}
current.next = target.next;
target.next = null;
target.prev = null;
break;
}
current = current.next;
}
}
public void insert(long data, int index) {
if (index < 0) {
throw new IllegalArgumentException("");
}
int i = -1;
Node current = first;
Node node = new Node(data);
if (isEmpty()) {
first.next = node;
last.prev = node;
return;
}
while (current != null) {
i++;
if (i == index) {
if (current.next != null) {
node.next = current.next;
current.next.prev = node;
} else {
last.prev = node;
}
node.prev = current;
current.next = node;
break;
}
current = current.next;
}
}
private class Node {
public long data;
public Node next;
public Node prev;
public Node() {
this.data = -1;
}
public Node(long data) {
this.data = data;
}
}
}