关于模板类的定义和使用List.h#ifndef LIST_H_#define LIST_H_template struct Node{T num;struct Node *next;};template class List{static const int MAX=10;private://T t[MAX];//int top;Node *front;Node *rear;int qsize;Node *now;public:/

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/06 04:06:48

关于模板类的定义和使用List.h#ifndef LIST_H_#define LIST_H_template struct Node{T num;struct Node *next;};template class List{static const int MAX=10;private://T t[MAX];//int top;Node *front;Node *rear;int qsize;Node *now;public:/
关于模板类的定义和使用
List.h
#ifndef LIST_H_
#define LIST_H_
template
struct Node{
T num;
struct Node *next;
};
template
class List{
static const int MAX=10;
private:
//T t[MAX];
//int top;
Node *front;
Node *rear;
int qsize;
Node *now;
public:
//List(int m);
List();
~List();//构造函数有new ,必须显示析构
void add(const T &t);
bool isEmpty()const;
bool isFull()const;
//void set(const T &t)const;
void visit(){
Node *p=front;
while((p++)!=nullptr)
{
cout

关于模板类的定义和使用List.h#ifndef LIST_H_#define LIST_H_template struct Node{T num;struct Node *next;};template class List{static const int MAX=10;private://T t[MAX];//int top;Node *front;Node *rear;int qsize;Node *now;public:/
/*
36  24  31  27  80  98  44  66  27  91  20  62
*/
#ifndef LIST_H_
#define LIST_H_
template <class T>
struct Node {
\x05T num;
\x05Node<T> *next;
};

template <class T>
class List {
\x05enum {MAX = 100};
private:
\x05Node<T> *front;
\x05Node<T> *rear;
\x05int qsize;
\x05Node<T> *now;
public:
\x05List();
\x05~List();
\x05void add(const T &t);
\x05bool isEmpty() const;
\x05bool isFull() const;
\x05//void set(const T &t)const;
\x05void visit(){
\x05\x05Node<T> *p = front;
\x05\x05while(p) {
\x05\x05\x05cout << p->num << "  ";
\x05\x05\x05p = p->next;
\x05\x05}
\x05\x05cout << endl;
\x05}
};
#endif

#include <iostream>
// #include "List.h"
using namespace std;

template <class T>
List<T>::List()\x05{
\x05front = rear = now = NULL;
\x05qsize = 0;
}

template <class T>
List<T>::List() {
\x05Node<T> *q,*p = front;
\x05while(p)\x05{
\x05\x05q = p->next;
\x05\x05delete p;
\x05\x05p = q;
\x05}
}

template <class T>//必须写出模板类,否则T无效
void List<T>::add(const T &t) {
\x05if(isFull()) {
\x05\x05cout << "List is full\n";
\x05\x05return;
\x05}
\x05Node<T> *newnode = new Node<T>;
\x05newnode->num = t;
\x05newnode->next = NULL;
\x05if(isEmpty()) {
\x05\x05front = rear = newnode;
\x05\x05++qsize;
\x05}
\x05else {
\x05\x05rear->next = newnode;
\x05\x05qsize++;
\x05\x05rear = newnode;
\x05}
\x05now = newnode;//令now指向当前节点
}

template <class T>
bool List<T>::isEmpty()const {
\x05return qsize == 0;
}
template <class T>
bool List<T>::isFull()const {
\x05return qsize == MAX;
}

// #include <iostream>
// #include "List.h"
// using namespace std;
int main () {
\x05List<int> arr;
\x05int a[] = {36,24,31,27,80,98,44,66,27,91,20,62};
\x05int i,n = sizeof(a)/sizeof(a[0]);
\x05for(i = 0; i < n; ++i)
\x05\x05arr.add(a[i]);
\x05arr.visit();
\x05cin.get();
\x05return 0;
}