From f55c76d0fb82c94eb996ddfc41a0758d11cb331b Mon Sep 17 00:00:00 2001 From: Samrat De Date: Thu, 21 May 2020 17:32:51 +0530 Subject: [PATCH] fix: Doubly Linked List algorithm bug --- data_structure/Doubly Linked List.cpp | 34 +++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/data_structure/Doubly Linked List.cpp b/data_structure/Doubly Linked List.cpp index 84a239d3f..a1b6da3ad 100644 --- a/data_structure/Doubly Linked List.cpp +++ b/data_structure/Doubly Linked List.cpp @@ -38,13 +38,37 @@ void insert(int x) void remove(int x) { node *t = start; - while (t->val != x) + while (t != NULL && t->val != x) { - t = t->next; + t = t-> next; } - t->prev->next = t->next; - t->next->prev = t->prev; - delete t; + if (t == NULL) + { + return; + } + // if first element is removed + if (t->prev == NULL) + { + if (t->next == NULL) + { + start = NULL; + } + else + { + start = t->next; + start->prev = NULL; + } + } + else if (t->next == NULL) + { + t->prev->next = NULL; + } + else + { + t->prev->next = t->next; + t->next->prev = t->prev; + } + delete t; } void search(int x)