So recently, I started to learn linked list in class and I am confused. She did a whole explanation and some examples, but it doesn't make sense. So for example I have a header file for the class Node and class AnyList.
I have a few functions that I need to implement, but it's a bit difficult for me. One of my functions is suppose to delete the last node of the list.
#ifndef ANYLIST_H
#define ANYLIST_H
#include<iostream>
#include <string>
usingnamespace std;
class Node
{
public:
Node() { next = nullptr; }
Node(const string& theData, Node *nextNode) : data(theData), next(nextNode){}
Node* getNext( ) const { return next; }
string getData( ) const { return data; }
void setData(const string& theData) { data = theData; }
void setNext(Node *nextNode) { next = nextNode; }
~Node(){}
private:
string data;
Node *next; //pointer that points to next node
};
class AnyList
{
public:
AnyList();
void insertBack(const string& newData);
void print() const;
void destroyList();
~AnyList();
/*************************************************************************/
// Declaration of function getFirstElement
Node getFirstElement() const;
// Declaration of function deleteFirstNode
string deleteFirstNode(const AnyList& list);
// Declaration of function deleteLastNode
string deleteLastNode(const AnyList& list) const;
// Declaration of function replaceData
string replaceData(const AnyList& list) const;
private:
Node *first; //pointer to point to the first node in the list
int numOfItems; //keeps track of number of nodes in the list
};
#endif
Your first step is to choose one of your triplicate posts and closeoff/greentick the others so that if anyone is decides to provide you with help their comments/help aren't wasted by duplicating effort. You only have to ask once, not 3 times.
Typically to delete the last one you have to handle the odd cases... totally empty (nothing to do), only 1 (delete it). If those are not true, you can muddle thru the list in a loop holding current and current's next (c, and cn). when cn-> next is null, you delete cn which is done via c: delete c->next; c-> next = null ...
You seem to have the code skeleton but otherwise I can't see much of your efforts.
So would it be something like this for deleteLastNode?
The way you delete the last node is wrong. It could be something like this :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Node* cn = first;
while (cn && cn->getNext() && cn->getNext()->getNext()) cn = cn->getNext();
if(cn == nullptr)
{
// Do something
}
elseif(cn->getNext())
{
// Delete the pointer we are checking
// Make cn point to null
}
else
{
// Delete the head pointer
}