Hi im writing a fill-in-the-blanks program and I am stuck on how to delete a node from a liked list. I am suppost to follow this psuedocode to finish the program. I think I am close to a solution, can anyone point out what im doing wrong?
The list already has values stored and the user is asked from Main to enter a value to delete (int item is passed to delete function). The commented code is the steps I am suppost to take to solve this. My attempt is the actual code. I must use the function template given.
// LinkedList.cpp
void LinkedList::deleteItem (int item)
{
ListElement *currPtr = head;
ListElement *deletePtr;
if (item == head->datum)
{
deletePtr = head;
head = head->next;
}
else
{
currPtr = head;
while (currPtr->next->datum != item)
{
head = head->next;
}
deletePtr = head;
}
delete head;
/*
If "item" is in the first node
{
Set a delete-pointer to the first node.
Change the "head" pointer to the second node.
}
Else
{
Set a current-pointer to the "head".
While current-pointer->next->datum is not equal to "item"
{
Set the current-pointer to the "next" node in the list.
}
Set a delete-pointer to the node to be deleted (Note: it is
the node after current-pointer).
Set the link member ("next") of the current-pointer to the
"next" node after delete-pointer.
}
Delete the node indicated by delete-pointer.
*/
}
// LinkedList.h
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <cstdlib>
#include <iostream>
using namespace std;
class LinkedList; // needed for friend line below
class ListElement
{
private:
int datum;
ListElement* next;
public:
ListElement (int, ListElement*);
int getDatum () const;
ListElement const* getNext () const;
friend class LinkedList; // gives LinkedList access to datum and next
};
class LinkedList
{
private:
ListElement* head;
public:
LinkedList ();
void insertItem (int);
void makeList ();
void appendItem (int);
void deleteItem (int);
void printList ();
};
#endif