可以用多种方法实现在C++中的栈机制,一种使用命名空间,一种使用Stack类,下面为大家介绍这2种栈机制的实现
1、命名空间方法
头文件:Stack.h
#ifndef STACK_H
#define STACK_H
#include <iostream>
namespace Stack
{
//定义栈空间大小
const int MaxSize = 200;
//初始化栈的SP指向为空栈的栈顶位置
int sp(MaxSize);
//定义栈段(这里指定了类型:int)
int stack[MaxSize];
//声明push操作
void push(const int& num);
//声明pop操作,注意这里的参数类型为引用
void pop(int& num);
}
void Stack::push(const int& num)
{
//栈满若继续push则友情提示
if(!sp)
std::cout << "Error: The stack is full!" << std::endl;
else
{
//以下两步完全仿照寄存器入栈过程
--sp;
*(stack + sp) = num;
}
}
void Stack::pop(int& num)
{
//栈空继续POP则友情提示
if(sp == MaxSize)
std::cout << "Error: The stack if empty!" << std::endl;
else
{
//模拟出栈过程
num = *(stack + sp);
++sp;
}
}
#endif
使用栈空间
源文件:main.cpp
#include <iostream>
#include "Stack.h"
using namespace Stack;
using namespace std;
int main()
{
int a(1), b(2), c(3);
cout << "Before push and pop:" << endl
<< "a = " << a << " b = " << b << " c = " << c << endl;
push(a); push(b); push(c);
pop(a); pop(b); pop(c);
cout << "After push and pop:\n"
<< "a = " << a << " b = " << b << " c = " << c << endl;
return 0;
}
2、类方法
头文件:cStack.h
注意,申请栈空间可以使用创建对象时初始化或者使用Stack类的application方法
#ifndef CSTACK_H
#define CSTACK_H
#include <iostream>
#include <cstddef>
class Stack
{
public:
Stack(size_t count)
{sp = count; application(count); remember = count;}
Stack(): remember(0) {}
~Stack()
{
delete stack;
}
public:
void push(const int&);
void pop(int&);
void application(size_t size);
private:
size_t remember;
size_t sp;
int *stack;
};
void Stack::application(size_t size)
{
stack = new int[size];
sp = size; remember = size;
}
void Stack::push(const int &element)
{
if(!remember)
std::cout << "Your stack size is zero,you should application first." << std::endl;
else if(!sp)
std::cout << "Error: stack is full" << std::endl;
else
{
--sp;
*(stack + sp) = element;
}
}
void Stack::pop(int &element)
{
if(!remember)
std::cout << "Your stack size is zero,you should application first." << std::endl;
else if(sp == remember)
std::cout << "Error: stack is empty" << std::endl;
else
{
element = *(stack + sp);
++sp;
}
}
#endif
源文件:main.cpp
#include <iostream>
#include "cStack.h"
using namespace std;
int main()
{
Stack st(10);
int a(1), b(2), c(3);
cout << "Before push and pop:\n"
<< "a = " << a << " b = " << b << " c = " << c << endl;
st.push(a); st.push(b); st.push(c);
st.pop(a); st.pop(b); st.pop(c);
cout << "After push and pop:\n"
<< "a = " << a << " b = " << b << " c = " << c << endl;
return 0;
}