Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added data-structures/linkedList
Binary file not shown.
41 changes: 41 additions & 0 deletions data-structures/linkedList.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -52,5 +91,7 @@ int main() {
list.addNode(4);
list.addNode(5);
list.printList();
list.deleteNode(3);
list.printList();
return 0;
}