Skip to content

Commit

Permalink
feat: Add delete by index method and print the output
Browse files Browse the repository at this point in the history
  • Loading branch information
VishwajeetVT committed Dec 2, 2024
1 parent 03f3466 commit 8f34b21
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,35 @@ public int deleteLast() {
return val;
}

public int delete(int index) {
if (index == 0) {
deleteFirst();
}

Node node = get(index);

int val = node.val;

if (node.next != null) {
node.prev.next = node.next;
node.next.prev = node.prev;
} else {
node.prev.next = null;
}
return val;
}

public Node get(int index) {
Node temp = head;
int i = 0;

while (temp != null && i < index) {
temp = temp.next;
i++;
}
return temp;
}

public void display() {
Node node = head;
Node last = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,17 @@ public static void main(String[] args) {
dd.insertFirst(7);
dd.insertLast(11);

dd.insert(10, 8);
dd.display();
// dd.insert(10, 8);
// dd.display();

System.out.println(dd.deleteFirst());
dd.display();
// System.out.println(dd.deleteFirst());
// dd.display();

System.out.println(dd.deleteLast());
// System.out.println(dd.deleteLast());
// dd.display();

dd.display();
System.out.println(dd.delete(3));
dd.display();
}
}

0 comments on commit 8f34b21

Please sign in to comment.