With help from the code below, define a member function for deleting a node at a
ID: 3724500 • Letter: W
Question
With help from the code below, define a member function for deleting a node at a specified position. A value of 0 for the position means that the first node in the list (the current head) is deleted. The function does nothing if the specified position is greater than or equal to the length of the list.void LinkedList::deleteNode(int data) { Node *tempNode = head; Node *preNode = NULL; if (!head) return; else if (head->data == data) { head = head->next; delete tempNode; } else { while (tempNode && tempNode->data != data) { preNode = tempNode; tempNode = tempNode->next; } if (tempNode) { preNode->next = tempNode->next; delete tempNode; } } } With help from the code below, define a member function for deleting a node at a specified position. A value of 0 for the position means that the first node in the list (the current head) is deleted. The function does nothing if the specified position is greater than or equal to the length of the list.
void LinkedList::deleteNode(int data) { Node *tempNode = head; Node *preNode = NULL; if (!head) return; else if (head->data == data) { head = head->next; delete tempNode; } else { while (tempNode && tempNode->data != data) { preNode = tempNode; tempNode = tempNode->next; } if (tempNode) { preNode->next = tempNode->next; delete tempNode; } } } With help from the code below, define a member function for deleting a node at a specified position. A value of 0 for the position means that the first node in the list (the current head) is deleted. The function does nothing if the specified position is greater than or equal to the length of the list.
void LinkedList::deleteNode(int data) { Node *tempNode = head; Node *preNode = NULL; if (!head) return; else if (head->data == data) { head = head->next; delete tempNode; } else { while (tempNode && tempNode->data != data) { preNode = tempNode; tempNode = tempNode->next; } if (tempNode) { preNode->next = tempNode->next; delete tempNode; } } }
Explanation / Answer
void LinkedList::deleteNode(int position)
{
int i;
Node *tempNode = head;
Node *ptr=head;
if (!head)
return;
int count=1;
//get total number of nodes in the list
while(ptr->next!=NULL)
{
ptr=ptr->next;
++count;
}
if(position<count)
{
//delete first node if position is 0
if (position==0)
{
head = head->next;
delete tempNode;
}
else
{
ptr=head;
for(i=0;i<position-1;++i)
ptr=ptr->next;
tempNode=ptr->next;
if(tempNode>next==NULL)
delete tempNode;
else
{
ptr->next=tempNode->next;
delete tempNode;
}
}
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.