Hi im working with linked list and i have to implement a function that deletes the duplicates of a number. for example if given 2 7 1 7 12 7
then the result should be 2 7 1 12
here is what I have:
#include <iostream>
using namespace std;
class NumberList
{
private:
// Declare a structure for the list
struct ListNode
{
double value; // The value in this node
struct ListNode *next; // To point to the next node
};
ListNode *head; // List head pointer
public:
// Constructor
NumberList()
{ head = NULL; }
// Destructor
~NumberList();
// Linked list operations
void appendNode(double);
void deleteDuplicates(double);
void displayList() const;
};
void NumberList::appendNode(double num)
{
ListNode *newNode; // To point to a new node
ListNode *nodePtr; // To move through the list
// Allocate a new node and store num there.
newNode = new ListNode;
newNode->value = num;
newNode->next = NULL;
// If there are no nodes in the list
// make newNode the first node.
if (!head)
head = newNode;
else // Otherwise, insert newNode at end.
{
// Initialize nodePtr to head of list.
nodePtr = head;
// Find the last node in the list.
while (nodePtr->next)
nodePtr = nodePtr->next;
// Insert newNode as the last node.
nodePtr->next = newNode;
}
}
void NumberList::displayList() const
{
ListNode *nodePtr; // To move through the list
// Position nodePtr at the head of the list.
nodePtr = head;
// While nodePtr points to a node, traverse
// the list.
while (nodePtr)
{
// Display the value in this node.
cout << nodePtr->value << endl;
// Move to the next node.
nodePtr = nodePtr->next;
}
}
// here is where i need help this function doesn't delete the repeated numbers
void NumberList::deleteDuplicates(double num)
{
ListNode* nodePtr=head;
int count=0;
while(nodePtr !=NULL)
{
count++;
if(nodePtr->value==num)
{
delete nodePtr;
}
else
nodePtr=nodePtr->next;
}}int main()
{
// Define a NumberList object.
NumberList list;
// Build the list with some values.
list.appendNode(2);
list.appendNode(7);
list.appendNode(1);
list.appendNode(7);
list.appendNode(12);
list.appendNode(7);
// Display the list.
cout << "Here are the initial values:\n";
list.displayList();
cout << endl;
//delete duplicates
list.deleteDuplicates(7);
cout<<"here is the new list:\n";
list.displayList();
cout<<endl;
return 0;
}