堆栈(stack)
堆栈的特性为先进后出(First In Last Out,FILO)。Push 压栈;Pop 出栈。
#include<windows.h>
#include<stdio.h>
//结构体--基本函数
struct stUnit
{
char szName[64];//存放名字的
};
//堆栈类
class clStack
{
private:
stUnit *mBuffer;//Buffer 缓冲器
unsigned int mBufSize;//缓存大小
unsigned int mCount;//这个很不稳当~~~不知道什么意思
public:
//---------------------------------构造函数-------------------------
clStack(unsigned int nBufSize): mBuffer(NULL),mBufSize(0),mCount(0)//私有变量初始化
{
if (nBufSize<10)
{
nBufSize=10;
}
mBufSize=nBufSize;
mBuffer=new stUnit[mBufSize] ;//缓存地址
}
//---------------------------------析构函数-------------------------
~clStack()
{
if (mBuffer !=NULL)
{
delete [] mBuffer;
mBuffer=NULL;
}
mCount=0;
mBufSize=0;
}
//---------------------------------进栈方法--------------------------
bool Push(stUnit Unit)//People[0]、People[1]、People[2]
{
if (mCount>=mBufSize)//mBufSize=10
{
return false;
}
mBuffer[mCount++]=Unit;//stUnit *mBuffer;//Buffer 缓冲器
//mCount= 1、2、3
return true;
}
//---------------------------------出栈方法--------------------------
bool Pop(stUnit &Unit)
{
if(mCount==0)
{
return false;
}
--mCount;
//mCount= 3、2、1
Unit=mBuffer[mCount];
return true;
}
};
int main(int argc,char *argv[])
{
//stUnit结构体 存放姓名;clStack 类(Push和Pop方法)
int loop;
clStack stack(10);//初始化缓存大小 mBufSize=10
stUnit People[3],Person;
strcpy(People[0].szName,"Peter");
strcpy(People[1].szName,"Mary");
strcpy(People[2].szName,"John");
printf("Push data into stack.\n");
//------------------------压栈---------------------------
for (loop=0;loop<3;loop++)
{
printf("%s\n",People[loop].szName);
stack.Push(People[loop]);//压栈
}
printf("\nPop data from stack.\n");
//------------------------出栈---------------------------
for (loop=0;loop<3;loop++)
{
stack.Pop(Person);
printf("%s\n",Person.szName);
}
return 0;
}