diff --git a/data-structures/linkedList b/data-structures/linkedList new file mode 100755 index 0000000..60bf8c3 Binary files /dev/null and b/data-structures/linkedList differ diff --git a/data-structures/linkedList.cpp b/data-structures/linkedList.cpp index 33ef17b..34f9b84 100644 --- a/data-structures/linkedList.cpp +++ b/data-structures/linkedList.cpp @@ -34,6 +34,45 @@ class LinkedList { currentNode->next = newNode; } + void deleteNode(int data) + { + if (this->head == NULL) + { + cout << "List is empty. Cannot delete." << endl; + return; + } + + // If the head node is to be deleted + if (this->head->data == data) + { + Node *temp = this->head; + this->head = this->head->next; + delete temp; + return; + } + + Node *currentNode = this->head; + Node *prevNode = NULL; + + // Traverse the list to find the node to delete + while (currentNode != NULL && currentNode->data != data) + { + prevNode = currentNode; + currentNode = currentNode->next; + } + + // If the node is not found + if (currentNode == NULL) + { + cout << "Node with value " << data << " not found." << endl; + return; + } + + // Remove the node + prevNode->next = currentNode->next; + delete currentNode; + } + void printList() { Node* currentNode = this->head; while (currentNode != NULL) { @@ -52,5 +91,7 @@ int main() { list.addNode(4); list.addNode(5); list.printList(); + list.deleteNode(3); + list.printList(); return 0; } \ No newline at end of file