Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added delete function in linked list #376

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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;
}