package linkedlist;
import linkedlist.Node;
public class DoubleLinkedList {
private Node firstNode = null;
public DoubleLinkedList(Object data) {
firstNode = new Node(data);
}
public void add(int index,Object data) {
Node currentNode = firstNode;
int currentIndex = 0;
try {
while (currentIndex != index) {
currentNode = currentNode.getNext();
currentIndex += 1;
}
nodeAdd(currentNode,data,currentIndex);
}
catch (java.lang.NullPointerException e) {
System.out.println("Index out of range");
}
}
public void add(Object data) {
Node currentNode = firstNode;
int currentIndex = 0;
while (currentNode.getNext() != null) {
currentNode = currentNode.getNext();
currentIndex += 1;
}
nodeAdd(currentNode,data,currentIndex);
}
public void nodeAdd(Node currentNode,Object data,int index) {
Node newNode = new Node(data);
if (index == 0) {
currentNode.setPrevious(newNode);
newNode.setNext(currentNode);
firstNode = newNode;
}
else {
newNode.setPrevious(currentNode);
currentNode.setNext(newNode);
}
System.out.println("Data added successfully!");
}
public Node remove(int index) {
Node currentNode = firstNode;
int currentIndex = 0;
try {
while (currentIndex != index) {
currentNode = currentNode.getNext();
currentIndex += 1;
}
nodeRemove(currentNode,currentIndex);
return currentNode.getPrevious();
}
catch (java.lang.NullPointerException e) {
System.out.println("Index out of range");
return firstNode;
}
}
public boolean remove(Object data) {
Node currentNode = firstNode;
int currentIndex = 0;
while (!currentNode.getData().equals(data)) {
currentNode = currentNode.getNext();
currentIndex += 1;
}
nodeRemove(currentNode,currentIndex);
return true;
}
private void nodeRemove(Node currentNode,int index) {
Node previousNode = currentNode.getPrevious();
Node nextNode = currentNode.getNext();
if (index == 0) {
nextNode.setPrevious(null);
firstNode = nextNode;
}
else {
previousNode.setNext(nextNode);
try {
nextNode.setPrevious(previousNode);
}
catch (java.lang.NullPointerException e) {
}
}
System.out.println("Data removed successfully!");
}
public String listIterator() {
Node currentNode = firstNode;
String data = "";
while (currentNode.getNext() != null) {
data += "\n" + currentNode.getData();
currentNode = currentNode.getNext();
}
data += "\n" + currentNode.getData();
return data;
}
}