C/C++栈的数组实现

作者在 2017-04-22 10:54:00 发布以下内容
#include<iostream>
#include<cstdlib>

using namespace std;
int *Array=NULL; 
int Count=0;

void Initial(int Size); //初始化栈
void Push(int Element); //入栈 
int GetStackLenth(void);//获取栈的个数 
void GetTopOfStack(void);//栈顶元素 
void Pop(void);          //出栈 
void Traverse(void);     //遍历 
void Destory(void);      //释放栈的内存 


int main()   ///测试 
{
int a[8]={15,65,13,81,26,34,88,55};
int Choose;
Initial(100);   //栈的初始化:开辟 
for(int i=0;i<8;i++)
   Push(a[i]);  //数组的数依次入栈 
Traverse();   //栈的遍历:从栈顶到栈尾依次输出 
cout <<endl <<"请输入你的选择:\n1.出栈 2.结束" <<endl ;
while(1)
{
cin >>Choose ;
switch(Choose)
{
case 1:
Pop();                          break;
case 2:
                               break;
default :
cout <<"输入选项有误!" <<endl ; break ;
}
if(Choose==2) break;
}
Traverse();   //发生变化后重新遍历,比对以前的栈
Destory();    //用完就释放内存 
return 0;
}


void Initial(int Size)
{
Array=(int *)malloc(sizeof(int)*Size);  //Size是栈的容纳个数 
if(Array==NULL)
   cout <<"空间不足! " <<endl ; 
}

void Push(int Element)  //入栈 
{
Array[Count++]=Element; 
}

int GetStackLenth(void)  //获得栈的个数 
{
return Count ;
}

void GetTopOfStack(void) //获得栈顶元素 
{
if(GetStackLenth()==0)
   cout <<"空栈 " <<endl ;
else 
   cout <<"栈顶元素为 " <<Array[Count-1] ; 
}

void Pop(void)  //出栈 
{
if(GetStackLenth()==0)
   cout <<"空栈!无法进行出栈操作 " <<endl ;
else
   Array[Count--]=0 ;
}


void Traverse(void) //遍历 
{
int Lenth=GetStackLenth();
if(Lenth==0)
   cout <<"空栈! " <<endl ;
else 
   while(Lenth--)
       cout <<Array[Lenth] <<' ' ;
   cout <<endl <<"遍历完毕 " ;
GetTopOfStack();
}

void Destory(void)
{
delete Array;
}
c++基础 | 阅读 1040 次
文章评论,共0条
游客请输入验证码