Here is an example of a simple List class I wrote. Follow the comments to understand what is going on. This uses the node structure I wrote about here.
Best of luck!
#include <cstdlib>
#include "Node.h" //Your Node class, see previous post
using namespace std;
class List
{
public:
List(){
head= NULL;
}
~List(){
destroyList(head);
}
void append(int d){
head = append(head, d);
}
void print(){
if (head != nullptr)
print(head);
}
void insertInOrder(int d){
head = insertInOrder(head, d);
}
bool findValue (int d){
return findValue(head, d);
}
int getSize(){
return getSize(head);
}
private:
Node *head; //Remember this struct from the previous post
/* Destroy the list
* We recursively call the destroy function to cycle through a list to the end.
* Once the end node is reached, it is deleted. Then as we progress back through
* our recursive call, each associated node is deleted from the end up.
* This is called by our destructor to clean everything up.
*/
void destroyList(Node *n){
if (n->next != nullptr){
destroyList(n->next);
}
delete n;
}
/* Add a Node to the end of a list
* Use recursion to cycle through the list to the end
* Once the end is reached, the next pointer of the last node will by nullptr.
* A new Node will then be inserted replacing that nullptr and chaining to the list
*/
Node* append(Node *n, int d){
if (n == nullptr){
return new Node(d);
}
else {
n->next= append(n->next, d);
}
return n;
}
/* Print the List
* Use recursion to loop through and print each Node in a list
*/
void print(Node *n){
cout << n->data << endl;
if (n->next != nullptr){
print(n->next);
}
}
/* Insert a Node in Numeric order
* Loop throug a list using recursion
* Once the inserting value is less than the current Node
* we know we need to insert the Node in that position
* else we keep cycling through
*/
Node* insertInOrder(Node *n, int d){
if (n == nullptr){
return new Node(d);
}
else if (d > n->data){
n->next= insertInOrder(n->next, d);
}
else {
Node* temp = n; //Temp copy
n = new Node(d); //Set the pointer to a new Node
n->next = temp; //Chain the original onto the new Node's next pointer
}
return n;
}
/* Find a Node
* Loop through the enitre list using recursion
* Return true once the Node value we want is found
*/
bool findValue(Node *n, int d){
if (n->data == d){
return true;
}
else if(n->next != nullptr){
return findValue(n->next, d);
}
return false;
}
/* Get the Size of a List
* Use recursion to cycle through the list
* all the while keeping a counter going of each Node encountered
*/
int getSize(Node *n, int i = 0){
if (n != nullptr){
++i;
return getSize(n->next, i);
}
return i;
}
};