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

Update deleteNode.cpp #195

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
45 changes: 45 additions & 0 deletions linked_list_problems/deleteNode.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,51 @@ void deleteNode( Node * node )
delete nextNode;
}

//Delete a Linked List node at a given position
void deleteNode(Node **head_ref, int position)
{

// If linked list is empty
if (*head_ref == NULL)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what about compare with nullptr

return;

// Store head node
Node* temp = *head_ref;

// If head needs to be removed
if (position == 0)
{

// Change head
*head_ref = temp->next;

// Free old head
free(temp);
return;
}

// Find previous node of the node to be deleted
for(int i = 0; temp != NULL && i < position - 1; i++)
temp = temp->next;

// If position is more than number of nodes
if (temp == NULL || temp->next == NULL)
return;

// Node temp->next is the node to be deleted
// Store pointer to the next of node to be deleted
Node *next = temp->next->next;

// Unlink the node from linked list
free(temp->next); // Free memory


temp->next = next;
}




int main()
{
Node * head = nullptr;
Expand Down