Write a function to delete an item in a // double linked list // NOTE: // A doub
ID: 3770647 • Letter: W
Question
Write a function to delete an item in a
// double linked list
// NOTE:
// A double linked list has two pointers in each node
// - p points to the next node
// - rp points to the previous node
// To delete a node in a DOUBLE LINKED LIST both forward and reverse
// pointers must be changed
// Be CERTAIN to consider the SPECIAL CASE of deleting the first node,
// since the parameter s must be changed (that is why it is passed
// as an alias parameter)
// Remember to return the deleted memory to the heap
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::ostream;
struct node {
int data;
node * p; // FORWARD LINK
node * rp; // REVERSE LINK
};
void deleteNode(node * & s, int itemToDelete) // Student Writes this Function
{
// PRECONDITION: itemToDelete is in the Double Linked List
return;
}
Explanation / Answer
void deleteNode(node * & currP, int itemToDelete) // Student Writes this Function
{
for (currP = head;
currP != NULL;
currP = currP->getNext()) {
if (currP->getData() == itemToDelete) { /* Found it. */
if (currP->getPrev() == NULL) {
head = currP->getNext();
} else if(currP->getNext() == NULL) { /* Remove from end */
currP->getPrev()->setNext(NULL);
} else {
currP->getPrev()->setNext(currP->getNext());
currP->getNext()->setPrev(currP->getPrev());
}
delete currP;
return true;
}
}
return false;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.