第21讲模板应用举例 教学目的与要求: 了解各类模板的特征。 掌握栈、队列、链表的应用 教学内容提要: 、栈类模板; 2、队列类模板; 2、链表类模板; 教学重点:链表类的声明和使用 教学难点:链表类的声明和使用。 教学进度:P228~P238 教学过程:
第 21 讲 模板应用举例 •教学目的与要求: 了解各类模板的特征。 掌握栈、队列、链表的应用。 •教学内容提要: 1、栈类模板; 2、队列类模板; 2、链表类模板; •教学重点: 链表类的声明和使用。 •教学难点:链表类的声明和使用。 •教学进度:P228~P238 •教学过程:
211栈类模板 入栈 出栈 入栈出栈 数组下标 数组下标 max max n a 栈顶 a 0 栈顶 0 a 0 初始状态(栈空) 般状态 入栈 出栈 数组下标 max ax+栈顶 a 相满状杰
栈顶 ┆ an ┆ a1 a0 入栈 出栈 数组下标 max n 1 0 一般状态 栈顶 入栈 出栈 数组下标 初始状态(栈空) max n 1 0 amax 栈顶 ┆ an ┆ a1 a0 入栈 出栈 数组下标 max n 1 0 栈满状态 21.1 栈类模板
例21.1使用栈类模板的使用。 #includeiostream. h> const int size=10 templateclass Type> //声明一个类模板 class stack[ public: void inito tos=0; void push( Type ch);//参数取Type类型 Type popo //返回类型取Type类型 private Type stck[size];//数组的类型为类型参数Type, 即可取任意类型 int tos template class Type> void stack<Type>:: push ( Type ob) if (tos==size) cout<< stack is full", return:I stckltos]=ob; tos++
例21.1 使用栈类模板的使用。 #include<iostream.h> const int size=10; template<class Type> //声明一个类模板 class stack{ public: void init(){ tos=0; } void push(Type ch); //参数取Type类型 Type pop(); //返回类型取Type类型 private: Type stck[size]; //数组的类型为类型参数Type, 即可取任意类型 int tos; }; template <class Type> void stack<Type>::push(Type ob) { if (tos==size){ cout<<"stack is full"; return ; } stck[tos]=ob; tos++; }
template class Type> Type stack <Type>:: pop o if (tos==o) cout< stack is empty return U tos return stckltos] main O) //定义字符堆栈 stack<char>s1,s2;//创建两个模板参数 为char型的对象 int s1 inito; s2. inito
template <class Type> Type stack <Type>::pop() { if (tos==0) { cout<<"stack is empty"; return 0; } tos--; return stck[tos]; } main() { //定义字符堆栈 stack <char> s1,s2; //创建两个模板参数 为char型的对象 int i; s1.init(); s2.init();
s1.push(a’);s2.push(x’); s1. push(b); s2. push(y') sl push(c); s2. push(z') for(i=0; 1<3; i++)cout<<"pop s1: <<sl pop(<<endl for(i=0; 1<3; i++) cout<< pop s2: <<s2. pop(<<endl //定义整型堆栈 stack<int>is1,is2;//创建两个模板参数为int型的对象 isl inito; is2 inito isl. push (1); is2. push (2) is1. push (3); is2 push (4) isl. push (5); is2. push (6) for(i=0;i<3;i++) cout< pop is1: <<isl. pop(<endl for(i=0;i<3;i++ cout< pop is2: <<is2 pop(<<endl return 0
s1.push('a'); s2.push('x'); s1.push('b'); s2.push('y'); s1.push('c'); s2.push('z'); for(i=0;i<3;i++) cout<<"pop s1: "<<s1.pop()<<endl; for(i=0;i<3;i++) cout<<"pop s2: "<<s2.pop()<<endl; //定义整型堆栈 stack <int> is1,is2; //创建两个模板参数为int型的对象 is1.init(); is2.init(); is1.push(1); is2.push(2); is1.push(3); is2.push(4); is1.push(5); is2.push(6); for (i=0;i<3;i++) cout<<"pop is1: "<<is1.pop()<<endl; for (i=0;i<3;i++) cout<<"pop is2: "<<is2.pop()<<endl; return 0; }