From 0915a8d818feea6d9bf709467822486c72e28f39 Mon Sep 17 00:00:00 2001 From: VishwajeetK Date: Mon, 2 Dec 2024 12:37:31 +0530 Subject: [PATCH] feat: Add insert function and print the output --- .../dsa/linkedlist/DoublyLinkedList.java | 27 +++++++++++++++++++ .../practice/dsa/linkedlist/DoublyMain.java | 2 ++ 2 files changed, 29 insertions(+) diff --git a/JavaDsaWithTest/src/main/java/org/practice/dsa/linkedlist/DoublyLinkedList.java b/JavaDsaWithTest/src/main/java/org/practice/dsa/linkedlist/DoublyLinkedList.java index 5ae65ce..15063b2 100644 --- a/JavaDsaWithTest/src/main/java/org/practice/dsa/linkedlist/DoublyLinkedList.java +++ b/JavaDsaWithTest/src/main/java/org/practice/dsa/linkedlist/DoublyLinkedList.java @@ -33,6 +33,33 @@ public void insertLast(int val) { node.prev = last; } + public void insert(int val, int after) { + Node p = find(after); + if (p == null) { + System.out.println("does not exists"); + return; + } + + Node node = new Node(val); + node.next = p.next; + p.next = node; + node.prev = p; + if (node.next != null) { + node.next.prev = node; + } + } + + public Node find(int value) { + Node node = head; + while (node != null) { + if (node.val == value) { + return node; + } + node = node.next; + } + return null; + } + public void display() { Node node = head; Node last = null; diff --git a/JavaDsaWithTest/src/main/java/org/practice/dsa/linkedlist/DoublyMain.java b/JavaDsaWithTest/src/main/java/org/practice/dsa/linkedlist/DoublyMain.java index ce59525..93fa21c 100644 --- a/JavaDsaWithTest/src/main/java/org/practice/dsa/linkedlist/DoublyMain.java +++ b/JavaDsaWithTest/src/main/java/org/practice/dsa/linkedlist/DoublyMain.java @@ -8,6 +8,8 @@ public static void main(String[] args) { dd.insertFirst(8); dd.insertFirst(7); dd.insertLast(11); + + dd.insert(10, 8); dd.display(); } }