Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create DoublyLInkedLIst_Implementation.java #878

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 109 additions & 0 deletions doubly_linked_list/DoublyLInkedLIst_Implementation.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
class Node<T> {
T data;
Node<T> next;
Node<T> prev;

public Node(T data) {
this.data = data;
this.next = null;
this.prev = null;
}
}

class DoublyLinkedList<T> {
private Node<T> head;
private Node<T> tail;
private int size;

public DoublyLinkedList() {
head = null;
tail = null;
size = 0;
}

public boolean isEmpty() {
return size == 0;
}

public int size() {
return size;
}

public void addFirst(T data) {
Node<T> newNode = new Node<>(data);
if (isEmpty()) {
head = newNode;
tail = newNode;
} else {
newNode.next = head;
head.prev = newNode;
head = newNode;
}
size++;
}

public void addLast(T data) {
Node<T> newNode = new Node<>(data);
if (isEmpty()) {
head = newNode;
tail = newNode;
} else {
newNode.prev = tail;
tail.next = newNode;
tail = newNode;
}
size++;
}

public void removeFirst() {
if (!isEmpty()) {
head = head.next;
if (head != null) {
head.prev = null;
} else {
tail = null;
}
size--;
}
}

public void removeLast() {
if (!isEmpty()) {
tail = tail.prev;
if (tail != null) {
tail.next = null;
} else {
head = null;
}
size--;
}
}

public void display() {
Node<T> current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
}

public class DoublyLInkedLIst_Implementation {
public static void main(String[] args) {
DoublyLinkedList<Integer> dll = new DoublyLinkedList<>();
dll.addFirst(1);
dll.addLast(2);
dll.addLast(3);
dll.addFirst(0);

System.out.println("Doubly Linked List:");
dll.display(); // Output: 0 1 2 3

dll.removeFirst();
dll.removeLast();

System.out.println("Doubly Linked List after removal:");
dll.display(); // Output: 1 2
}
}