//
//StackDemo Define the entry point for the console application.
//
# include <windows.h>
# include <stdio.h>
//基本数据
struct stUnit
{
char szName[64];
};
//堆栈类
class clStack
{
private:
stUnit *mBuffer;
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){ //将数据存入堆栈中
if (mCount>=mBufSize) //检查堆栈是否是满的
{
return false;
}
mBuffer[mCount++]=Unit;
return true;
}
bool Pop(stUnit& Unit){
if (mCount==0) //检查堆栈是否是空的
{
return false;
}
--mCount;
Unit=mBuffer[mCount];
return true;
}
};
int main(int argc,char* argv[])
{
int loop;
clStack Stack(10);
stUnit People[3];
stUnit Person;
//rson.szName="fdfdfdfd";
//trcpy(Person.szName,"fdfdfdfd");
strcpy(People[0].szName,"Peter"); //建立三个人物的数据
strcpy(People[1].szName,"Mary");
strcpy(People[2].szName,"John");
//push data into stack.
printf("push data into stack. ");
for (loop=0;loop<3;loop++)
{
printf("%s ",People[loop].szName);
Stack.Push(People[loop]);
}
//pop data from stack.
printf(" Pop data from stack. ");
for (loop=0;loop<3;loop++)
{
if(Stack.Pop(Person))
{
printf("%s ",Person.szName);
}
}
return 0;
}
//StackDemo Define the entry point for the console application.
//
# include <windows.h>
# include <stdio.h>
//基本数据
struct stUnit
{
char szName[64];
};
//堆栈类
class clStack
{
private:
stUnit *mBuffer;
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){ //将数据存入堆栈中
if (mCount>=mBufSize) //检查堆栈是否是满的
{
return false;
}
mBuffer[mCount++]=Unit;
return true;
}
bool Pop(stUnit& Unit){
if (mCount==0) //检查堆栈是否是空的
{
return false;
}
--mCount;
Unit=mBuffer[mCount];
return true;
}
};
int main(int argc,char* argv[])
{
int loop;
clStack Stack(10);
stUnit People[3];
stUnit Person;
//rson.szName="fdfdfdfd";
//trcpy(Person.szName,"fdfdfdfd");
strcpy(People[0].szName,"Peter"); //建立三个人物的数据
strcpy(People[1].szName,"Mary");
strcpy(People[2].szName,"John");
//push data into stack.
printf("push data into stack. ");
for (loop=0;loop<3;loop++)
{
printf("%s ",People[loop].szName);
Stack.Push(People[loop]);
}
//pop data from stack.
printf(" Pop data from stack. ");
for (loop=0;loop<3;loop++)
{
if(Stack.Pop(Person))
{
printf("%s ",Person.szName);
}
}
return 0;
}
本文通过一个简单的C++程序演示了栈的基本操作,包括压栈和出栈,并使用自定义的结构体作为存储单元。
2704

被折叠的 条评论
为什么被折叠?



