您的位置:首页 > 编程语言 > C语言/C++

C++栈的初始化,入栈,出栈,获取栈顶元素等操作

2016-02-26 22:21 701 查看
栈的一些性质:

1.栈为空不可以出栈

2.栈顶元素先出

3.新元素插入栈顶

栈的初始化:

#include<iostream>
#include<string>
using namespace std;
template <class Type>    //模板,表示可以"动态"定义Stack中某些数据元素的类型,这样的话可以增加代码的重用性
class Stack{
private:
Type *urls;       //定义指向整型的指针,从而动态开辟内存
int max_size,top_index;       //max_size表示栈的最大容量,top_index指向栈顶元素
public:
Stack(int length_input){     //构造函数
urls = new Type [length_input];   //动态开辟内存
max_size = length_input;          //为max_size赋值,表示栈的最大容量
top_index = -1;                  //一开始栈为空,栈顶指针赋值为-1
}
~Stack(){
delete [] urls;             //析构函数,删除动态开辟的内存
}
};
int main() {
int n;
cin >> n;
Stack <string> stack (n);         //声明一个string类的栈,栈的最大容量为n
return 0;
}
入栈,出栈以及获取栈顶元素:

#include<iostream>
#include<string>
using namespace std;
template <class Type>    //模板,表示可以"动态"定义Stack中某些数据元素的类型,这样的话可以增加代码的重用性
class Stack{
private:
Type *urls;       //定义指向整型的指针,从而动态开辟内存
int max_size,top_index;       //max_size表示栈的最大容量,top_index指向栈顶元素
public:
Stack(int length_input){     //构造函数
urls = new Type [length_input];   //动态开辟内存
max_size = length_input;          //为max_size赋值,表示栈的最大容量
top_index = -1;                  //一开始栈为空,栈顶指针赋值为-1
}
~Stack(){
delete [] urls;             //析构函数,删除动态开辟的内存
}
bool push(const Type &element){         //为了节省内存,则直接使用引用操作,引用即为变量的别名
if(top_index >= max_size-1){        //栈满,入栈失败
return false;
}
++top_index;            //栈顶指针上移
urls[top_index] = element;
return true;
}
bool pop(){
if(top_index < 0){    //栈空,出栈失败
return false;
}
--top_index;        //栈顶指针下移
return true;
}
Type top(){
assert(top_index >= 0);   //断言操作,不满足括号内条件时,则程序终止
return urls[top_index];
}
};
int main() {
int n, m;
cin >> n >> m;
Stack<string> stack(n);
for(int i = 1;i <= m;i++){        //总共执行m次操作,为了方便,我们这里假设当opr == 0时,执行插入操作;当opr == 1时,执行出栈操作;
//当opr == 2时,执行获取栈顶元素操作。
int opr;
cin >> opr;
if(opr==0){
string element;
cin >> element;
if(stack.push(element)){
cout << "push success!" << endl;
}
else{
cout << "push failed!" << endl;
}
}
else if(opr == 1){
if (stack.pop()) {
cout << "pop success!" << endl;
}
else {
cout << "pop failed!" << endl;
}
}
else if (opr == 2) {
cout << stack.top() << endl;
}
}
return 0;
}
运行示例:



如有错误,还请指正,O(∩_∩)O谢谢
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: