请尝试以下操作:
#include <iostream>
#include <string>
#include <stdexcept>
#include <initializer_list> // C++11 and later only
template <typename E>
class SLinkedList {
public:
SLinkedList();
SLinkedList(const E *vals, int num_vals);
SLinkedList(std::initializer_list<E> vals); // C++11 and later only
~SLinkedList();
bool empty() const;
int size() const;
E& front();
void addFront(const E &e);
void removeFront();
void printList() const;
private:
class SNode
{
public:
E elem;
SNode *next;
SNode(const E &e, SNode *n = NULL);
};
SNode* head;
int n; // number of items
};
template <typename E>
SLinkedList<E>::SNode::SNode(const E &e, SLinkedList<E>::SNode *n)
: elem(e), next(n) { }
template <typename E>
SLinkedList<E>::SLinkedList()
: head(NULL), n(0) { }
template <typename E>
SLinkedList<E>::SLinkedList(const E *vals, int num_vals)
: head(NULL), n(0)
{
for (int i = num_vals-1; i >= 0; --i)
addFront(vals[i]);
/* alternatively:
SNode **ptr = &head;
for (int i = 0; i < num_vals; ++i)
{
*ptr = new SNode(vals[i]);
++n;
ptr = &((*ptr)->next);
}
*/
}
template <typename E>
SLinkedList<E>::SLinkedList(std::initializer_list<E> vals)
: head(NULL), n(0)
{
const E *begin = vals.begin(), *iter = vals.end();
while (iter != begin)
addFront(*(--iter));
/* alternatively:
const E *iter = vals.begin(), *end = vals.end();
SNode **ptr = &head;
while (iter != end)
{
*ptr = new SNode(*iter);
++n;
ptr = &((*ptr)->next);
}
*/
}
template <typename E>
SLinkedList<E>::~SLinkedList()
{
while (head)
removeFront();
}
template <typename E>
bool SLinkedList<E>::empty() const
{
return (!head);
}
template <typename E>
int SLinkedList<E>::size() const
{
return n;
}
template <typename E>
E& SLinkedList<E>::front()
{
if (!head) throw std::length_error("empty list");
return head->elem;
}
template<typename E>
void SLinkedList<E>::printList() const
{
SNode *p = head;
while (p)
{
std::cout << p->elem << " ";
p = p->next;
}
std::cout << std::endl;
}
template <typename E>
void SLinkedList<E>::addFront(const E& e)
{
head = new SNode(e, head);
++n;
}
template <typename E>
void SLinkedList<E>::removeFront()
{
SNode* old = head;
if (!old) throw std::length_error("empty list");
head = old->next;
--n;
delete old;
}
Live Demo