#include <iostream> using std::cout; using std::cin; using std::endl; using std:
ID: 3770645 • Letter: #
Question
#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
};
ostream & operator<<( ostream &, const node *); // Written by Instructor
void addFront2( node * & start, int); // Written by Instructor
void cleanUp2( node *); // Written by Instructor
void deleteNode(node * & s, int itemToDelete); // WRITTEN BY STUDENT
void q2()
{
cout << " QUESTION 2 STARTING**********" << endl;
node * a;
a = NULL;
addFront2(a,400);
addFront2(a,300);
addFront2(a,200);
addFront2(a,100);
cout << "BEFORE a is " << a << endl << endl;
deleteNode(a,300);
cout << "AFTER deleting 300 a is " << a << endl << endl;
deleteNode(a,100);
cout << "AFTER deleting 100 a is " << a << endl << endl;
deleteNode(a,400);
cout << "AFTER deleting 400 a is " << a << endl << endl;
deleteNode(a,200);
cout << "AFTER deleting 200 a is " << a << endl << endl;
cleanUp2(a);
}
void deleteNode(node * & s, int itemToDelete) // Student Writes this Function
{
// PRECONDITION: itemToDelete is in the Double Linked List
return;
}
void addFront2( node * & start, int x)
{
node * t = new node;
t->data = x;
if( start != NULL )
{
t->p = start;
t->rp = NULL;
start->rp = t;
}
else
{
t->p = NULL;
t->rp = NULL;
}
start = t;
}
void cleanUp2( node * s)
{
node * walker, * prev;
walker = s;
while ( walker != NULL )
{
prev = walker;
walker = walker->p;
delete prev;
}
}
ostream & operator<<(ostream & w, const node * s)
{
const node * walker = s;
const node * trailer = walker;
w << "Forward Print " << endl << " ";
if ( s==NULL)
{
w << "EMPTY LIST";
}
else
{
while ( walker != NULL )
{
w << walker->data << ' ';
trailer = walker;
walker = walker->p;
}
}
w << endl << "Reverse Print " << endl << " ";
if ( trailer == NULL )
{
w << "EMPTY LIST";
return w;
}
while ( trailer != NULL)
{
w << trailer->data << ' ';
trailer = trailer->rp;
}
return w;
}
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
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.