- 除了队列,C++中另外一种重要数据结构就是栈,这是一种先入后出的结构,可以理解为一个桶,先放进去的东西后拿出来。
- 现在修改“队列”的相关函数,使其变为栈相关代码如下;
栈的相关成员函数:
#ifndef Stack_h_
#define Srtack_h_
#include "Coordinate.h"
class Stack
{
public:
Stack(int StackCapaticy);
~Stack();
void clearStack();
bool emptyStack();
bool fullStack();
int StackLen();
bool enterStack(Coordinate element);
bool pushStack(Coordinate &element);
void travelStack();
private:
int m_iStackCapaticy;
int m_iStackLen;
int m_iTop;
Coordinate* m_pStack;
};
#endif
栈的相关成员函数的实现
#include <iostream>
#include "Stack.h"
using namespace std;
Stack::Stack(int StackCapaticy)//此为构造函数,将栈的相关参数全部初始化
{
m_iStackCapaticy = StackCapaticy;//初始化栈空间容量参数
m_pStack = new Coordinate[m_iStackCapaticy];//堆上分配一段内存
m_iStackLen = 0;//栈长为0
m_iTop=0;//栈顶也是0,还没有元素入栈
}
Stack::~Stack()//析构函数,释放堆上内存
{
delete[]m_pStack;
m_pStack = NULL;
}
void Stack::clearStack()//清除栈的空间
{
m_iTop = 0;//栈顶回到栈底
m_iStackLen = 0;//栈长也为0
}
bool Stack::emptyStack()//判断栈是否为空栈,删除栈元素的时候要调用
{
return m_iStackLen ==0? true : false;
}
bool Stack::fullStack()//判断栈是否为满栈,往栈中加元素的时候要调用
{
return m_iStackLen == m_iStackCapaticy ? true : false;
}
int Stack::StackLen()//显示栈的长度
{
return m_iStackLen;
}
bool Stack::enterStack(Coordinate element)//元素入栈
{
if (fullStack()==true)
{
return false;
}
else if (fullStack()==false)
{
m_pStack[m_iTop] = element;
m_iTop++;
m_iStackLen++;
return true;
}
}
bool Stack::pushStack(Coordinate &element)//元素出栈
{
if (emptyStack() == true)
{
return false;
}
else if (emptyStack() == false)
{
element = m_pStack[m_iTop];
m_iTop--;
m_iStackLen--;
return true;
}
}void Stack::travelStack()//遍历栈中的所有元素
{
for (int i = 0; i < m_iStackLen; i++)
{
m_pStack[i].printInfo();
}
}
下面的函数修改可以改变传入栈的数据类型,想传什么数据就穿什么数据(我这里以传入坐标为例子)
#ifndef Coordinate_h_
#define Coordinate_h_
class Coordinate
{
public:
Coordinate(int x=0, int y=0);
void printInfo();
private:
int m_iX;
int m_iY;
};
#endif
#include "Coordinate.h"
#include <iostream>
using namespace std;
Coordinate::Coordinate(int x, int y )
{
m_iX=x;
m_iY=y;
}
void Coordinate::printInfo()
{
cout <<"("<< m_iX << " ," << m_iY <<")"<< endl;
}
下面是主函数的实现栈的元素传入传出,遍历。
#include "Stack.h"
#include "Coordinate.h"
#include <stdlib.h>
#include <iostream>
using namespace std;
int main()
{
Stack* p = new Stack(4);
Coordinate c1(1, 1);
Coordinate c2(2, 2);
Coordinate c3(3, 3);
Coordinate c4(4, 4);
Coordinate c5(0, 0);
p->enterStack(c1);
p->enterStack(c2);
p->enterStack(c3);
p->enterStack(c4);
p->pushStack(c5);
p->travelStack();
cout << p->StackLen() << endl;
system("pause");
return 0;
}