In: Computer Science
// C++ Doubly linked list
class clinknode{
friend class DList;
public:
clinknode(){next = prev=0;data =0;}
protected:
clinknode *next;
clinknode *prev;
int data;
}
class DList{
public:
DList(){first = last = 0;}
void insertFront(int key);
bool found(int key){ return search(key)!=0;}
void deleteAll(int key);
// other list functions...
private:
clinknode *search(int);
clinknode *first;
clinknode *last;
}
(20 points) Write the code for the deleteAll (int key) member function. It takes a key value and deletes all of the data in the list with that value. Make sure to preserve the integrity of the list. If no member with that value is in the list, this function should do nothing.
#include <iostream>
using namespace std;
class clinknode{
friend class DList;
public:
clinknode(){next = prev=0;data =0;}
clinknode(int value){next = prev=0;data=value;}
protected:
clinknode *next;
clinknode *prev;
int data;
};
class DList{
public:
DList(){first = last = 0;}
//implemented for testing purpose
void insertFront(int key)
{
clinknode *node = new clinknode(key);
if( first == 0)
{
first = node;
}
else
{
node->next = first;
first->prev = node;
first = node;
}
}
bool found(int key){ return search(key)!=0;}
void deleteAll(int key)
{
clinknode *temp;
clinknode *prev = NULL;
clinknode *next;
for (temp = first; temp != NULL; temp = next) {
next = temp->next;
if (temp->data != key) {
prev = temp;
continue;
}
if (prev != NULL)
prev->next = next;
else
first = next;
delete temp;
}
}
//added this function for testing purpose
void display()
{
clinknode *a;
cout << "Values in list" << endl;
a=first;
while(a) {
cout <<a->data
<<endl;
a=a->next;
}
}
// other list functions...
private:
clinknode *search(int);
clinknode *first;
clinknode *last;
};
int main()
{
DList lt;
lt.insertFront(10);
lt.insertFront(20);
lt.insertFront(10);
lt.insertFront(5);
lt.insertFront(10);
lt.display();
lt.deleteAll(10);
lt.display();
lt.deleteAll(30);
lt.display();
return 0;
}
output:
Values in list
10
5
10
20
10
Values in list
5
20
Values in list
5
20