From e9195df7d0d6e00c1c4ba88969600444a5f56bc3 Mon Sep 17 00:00:00 2001 From: Bhavish <111994995+bhavish95@users.noreply.github.com> Date: Sun, 15 Oct 2023 01:34:17 +0530 Subject: [PATCH] Create DoublyLInkedLIst_Implementation.java --- .../DoublyLInkedLIst_Implementation.java | 109 ++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 doubly_linked_list/DoublyLInkedLIst_Implementation.java diff --git a/doubly_linked_list/DoublyLInkedLIst_Implementation.java b/doubly_linked_list/DoublyLInkedLIst_Implementation.java new file mode 100644 index 00000000..2046a2be --- /dev/null +++ b/doubly_linked_list/DoublyLInkedLIst_Implementation.java @@ -0,0 +1,109 @@ +class Node { + T data; + Node next; + Node prev; + + public Node(T data) { + this.data = data; + this.next = null; + this.prev = null; + } +} + +class DoublyLinkedList { + private Node head; + private Node 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 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 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 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 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 + } +}