栈的介绍:
栈(stack),是一种线性存储结构,它有以下几个特点:
(1) 栈中数据是按照"
后进先出
方式进出栈的。
(2) 向栈中添加/删除数据时,只能从
栈顶
进行操作。
栈通常包括的三种操作:
push
、
peek
、
pop
。
push
-- 向栈中添加元素。
peek
-- 返回栈顶元素。(取出)
pop -- 返回并删除栈顶元素的操作。(删除)
C++的STL中本身就包含了
stack
类,基本上该
stack
类就能满足我们的需求,所以很少需要我们自己来实现。
本部分介绍2种C++实现。
1. C++实现一:数组实现的栈,能存储任意类型的数据。
2. C++实现二:C++的 STL 中自带的"栈"(stack)的示例。
这是ArrayStack.h文件
//数组实现的栈,能存储任意类型的数据
#ifndef ARRAY_STACK_HXX
#define ARRAY_STACK_HXX
#include <iostream>
#include "ArrayStack.h"
using namespace std;
//模板类
template<class T>
class ArrayStack{
public:
ArrayStack();
~ArrayStack();
void push(T t);//向栈中添加一个t元素
T peek();//向栈中取出一个元素
T pop();//在栈中删除一个元素
int size();//大小
int isEmpty();//判断是否为空
private:
T *arr;//数组?
int count;
};
// 创建“栈”,默认大小是12
template<class T>
ArrayStack<T>::ArrayStack() //这里面就是比普通的
{
arr = new T[12];
if (!arr)
{
cout<<"arr malloc error!"<<endl;
}
}
// 销毁“栈”
template<class T>
ArrayStack<T>::~ArrayStack()
{
if (arr)
{
delete[] arr;
arr = NULL;
}
}
// 将val添加到栈中
//向栈中添加一个元素
template<class T>
void ArrayStack<T>::push(T t)
{
//arr[count++] = val;
arr[count++] = t;
}
// 返回“栈顶元素值”
template<class T>
T ArrayStack<T>::peek()
{
return arr[count-1];
}
// 返回“栈顶元素值”,并删除“栈顶元素”
template<class T>
T ArrayStack<T>::pop()
{
int ret = arr[count-1];
count--;
return ret;
}
// 返回“栈”的大小
template<class T>
int ArrayStack<T>::size()
{
return count;
}
// 返回“栈”是否为空
template<class T>
int ArrayStack<T>::isEmpty()
{
return size()==0;
}
#endif
这是main.cpp文件
#include <iostream>
#include "ArrayStack.h"
using namespace std;
int main()
{
int tmp=0;
ArrayStack<int> *astack = new ArrayStack<int>();
cout<<"main"<<endl;
// 将10, 20, 30 依次推入栈中
astack->push(10);
astack->push(20);
astack->push(30);
// 将“栈顶元素”赋值给tmp,并删除“栈顶元素”
tmp = astack->pop();
cout<<"tmp="<<tmp<<endl;
// 只将“栈顶”赋值给tmp,不删除该元素.
tmp = astack->peek();
astack->push(40);
while (!astack->isEmpty())
{
tmp = astack->pop();
cout<<tmp<<endl;
}
system("pause");
return 0;
}
C++实现二:C++的 STL 中自带的"栈"(stack)的示例
#include <iostream>
#include <stack>
using namespace std;
/*
* C++ 语言: STL 自带的“栈”(stack)的示例。
*/
int main ()
{
int tmp=0;
stack<int> istack;//定义为int类型的函数
// 将10, 20, 30 依次推入栈中
istack.push(10);
istack.push(20);
istack.push(30);
// 将“栈顶元素”赋值给tmp,并删除“栈顶元素”
istack.pop();
// 只将“栈顶”赋值给tmp,不删除该元素.
tmp = istack.top();
istack.push(40);
while (!istack.empty())
{
tmp = istack.top();
istack.pop();
cout<<tmp<<endl;
}
system("pause");
return 0;
}