template<class T>class SList {public: SList():head_(0),size(0) {} template<class In> SList(In first, In last); void push_front(const T& val); void pop_front(); T front()const; void reverse(); bool empty()const;
void show()const;
~SList();private: struct Node {
Node *next_; T el_; };
Node *head_; int size;};
template<class T>template<class In>SList<T>::SList(In first, In last):head_(0),size(0) { while( first != last) { push_front(*first++); }}
template<class T>void SList<T>::push_front(const T &val) { Node *newNode = new Node; newNode->el_ = val; newNode->next_ = head_; head_ = newNode; ++size;}
template<class T>void SList<T>::pop_front() { if ( !empty()) { Node *p = head_; if (p->next_) { head_ = head_->next_; delete p; } else { delete head_; head_ = NULL; }
--size; }}
template<class T>T SList<T>::front() const {
if (!empty()) { return head_->el_; }}
template<class T>bool SList<T>::empty()const { return 0 == size;}
template<class T>SList<T>::~SList() { while(head_) { Node *p = head_; head_ = head_->next_; delete p; --size; }}
template<class T>void SList<T>::show()const {
Node *p = head_; while(p) { std::cout<<p->el_<<"/n"; p = p->next_; }}
#include "Temp.cpp"#include<vector>
int _tmain(int argc, _TCHAR* argv[]){
int a[5] = {1,2,3,4,5}; std::vector<double> data(a, a + 5); //SList<int> S(a,a + 5 ); SList<int> S(data.begin(), data.end() );
S.show(); system("pause"); return 0;}
上面的Node 也可以在类的外面定义
如:
template<class T>
struct SList<T>::Node {
Node *next_;
T el_;
};