数据结构 栈
讲解链接https://blog.51cto.com/9291927/2063393
https://blog.csdn.net/hguisu/article/details/7674195

1.栈的概念
store a set of elements in a particular order
LAST IN FIRST OUT

2.栈的基本操作
create : create a stack leaving it empty
empty(): test whether a stack is empty
push():push a new entry onto the top of the stack provided the stack is not full
pop():pop an entry off the top of the stack provided the stack is not empty
top():retrieve the top entry from the stack provided the stack is not empty
3.基于数组的栈的实现
数组尾为栈顶,数组头为栈底

MyStack.h

MyStack.cpp
MyStack():

empty():

Push():

Top():

Pop():

利用栈对数组逆序


实现一个满足任意数据类型的栈
方法1 typedef

方法2 :templates 模板
C++支持 function template
class template
C++中定义函数模板
template <class类型形参名1,...,class类型形参名n>
返回类型函数模板名(形参表){
函数体
}
e.g. template<class T>
T Abs(T n){
return n<0?-n:n
}
实例
#include<iostream>
using namespace std;
template <class type>
type Abs(type n){
return n<0?-n:n;
}int main(){
cout << "Absolute value of -5 is "<< Abs<int>(-5); //<int>称为模板函数的实例化
cout << endl;
cout << "Absolute value of -5.6 is " << Abs<int>(-5.6);
cout << endl;
}
在类外定义模板类的成员函数
template<形参1的说明,...,形参n的说明>
返回类型 类名<形参1的名字,...,形参n的名字>函数名(列表)
{
函数体
}
使用类模板实现数组逆序
#include<MyStack.cpp>//attention especially for template
上面的例子用模板类实现
MyStack.h
MyStack.cpp



main.cpp




浙公网安备 33010602011771号