DLL
By : Khaled
Source Code :
class DLL {
DNode head;
DNode tail;
static class DNode {
int data;
DNode prev;
DNode next;
DNode(int d) {
data = d;
prev = null;
next = null;
public void addToHead(int i) {
DNode newNode = new DNode(i);
if (head == null) {
head = newNode;
tail = newNode;
} else {
newNode.next = head;
head.prev = newNode;
head = newNode;
public void addToTail(int i) {
DNode newNode = new DNode(i);
if (tail == null) {
head = newNode;
tail = newNode;
} else {
newNode.prev = tail;
tail.next = newNode;
tail = newNode;
public void addToInside(int i, int j) {
DNode newNode = new DNode(i);
DNode currentNode = head;
while (currentNode != null) {
if (currentNode.data == j) {
newNode.next = currentNode.next;
newNode.prev = currentNode;
currentNode.next = newNode;
if (newNode.next != null) {
newNode.next.prev = newNode;
if (currentNode == tail) {
tail = newNode;
break;
currentNode = currentNode.next;
public void deleteFromHead() {
if (head == null) {
return;
head = head.next;
if (head != null) {
head.prev = null;
} else {
tail = null;
public void deleteFromTail() {
if (tail == null) {
return;
tail = tail.prev;
if (tail != null) {
tail.next = null;
} else {
head = null;
public void deleteFromMid(int n) {
DNode currentNode = head;
while (currentNode != null) {
if (currentNode.data == n) {
if (currentNode == head) {
deleteFromHead();
} else if (currentNode == tail) {
deleteFromTail();
} else {
currentNode.prev.next = currentNode.next;
currentNode.next.prev = currentNode.prev;
break;
currentNode = currentNode.next;
public void print() {
DNode currentNode = head;
while (currentNode != null) {
System.out.print(currentNode.data + " ");
currentNode = currentNode.next;
}
System.out.println();
public boolean search(int n) {
DNode currentNode = head;
while (currentNode != null) {
if (currentNode.data == n) {
return true;
currentNode = currentNode.next;
return false;
public class DLL_Test {
public static void main(String[] args) {
DLL dll = new DLL();
dll.addToHead(3);
dll.addToTail(5);
dll.addToInside(4, 3);
dll.print(); // Output: 3 4 5
dll.deleteFromMid(4);
dll.print(); // Output: 3 5
if(dll.search(5)){
System.out.println("the element found in DLL");
}
else
System.out.println("the element not found in DLL");
if(dll.search(2)){
System.out.println("the element found in DLL");
else
System.out.println("the element not found in DLL");
Output :
Screenshot :