I have to create a constructor that allows a new linked list to be populated with ten consecutive values, starting at 0. Then I need to print the list! So i want to check if the functions I wrote for those are ok.
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
template <typename E> class SLinkedList; // forward declaration to be used when declaring SNode
template <typename E>
class SNode {
private:
E elem;
SNode<E> *next;
friend class SLinkedList<E>;
};
template <typename E>
class SLinkedList {
public:
SLinkedList();
SLinkedList(SNode<E>* v); //What I need help with
~SLinkedList();
bool empty() const;
E& front();
void printList(SLinkedList<E> &list); //what i need help with
void addFront(const E& e);
void removeFront();
int size() const;
private:
SNode<E>* head;
int n; // number of items
};
template <typename E>
SLinkedList<E>::SLinkedList() // constructor
: head(NULL), n(0) { }
template <typename E>
SLinkedList<E>::SLinkedList(SNode<E>* v){ //WHat I Need Help With
SNode<E>* v = new SNode<E>;
for (int i = 0; i < 10; i++)
v->elem = i;
}
template <typename E>
bool SLinkedList<E>::empty() const
{
return head == NULL; // can also use return (n == 0);
}
template <typename E>
E& SLinkedList<E>::front()
{
if (empty()) throw length_error("empty list");
return head->elem;
}
template <typename E>
SLinkedList<E>::~SLinkedList()
{
while (!empty()) removeFront();
}
template<typename E>
void SLinkedList<E>::printList(SLinkedList<E> &list) //What I need help with
{
for (int i = 0; i < list.size(); i++)
{
cout << list << " ";
}
cout << endl;
}
template <typename E>
void SLinkedList<E>::addFront(const E& e) {
SNode<E>* v = new SNode<E>; // create new node
v->elem = e; // store data
v->next = head; // head now follows v
head = v; // v is now the head
n++;
}
template <typename E>
void SLinkedList<E>::removeFront() {
if (empty()) throw length_error("empty list");
SNode<E>* old = head;
head = old->next;
delete old;
n--;
}
template <typename E>
int SLinkedList<E>::size() const {
return n;
}
std::iota()is for (or perhapsstd::generate_n()). Consider using a standard algorithm instead of reinventing wheels. \$\endgroup\$