标签:bsp break end let real exit increase stack free
#define STACKSIZE_ 100
#define STACKINCREASEMENT 10
#include<iostream>
using namespace std;
typedef struct stack
{
char *base;
char *top;
int stacksize;
}S;
S CreateStack()
{
S s;
s.base=(char *)malloc(sizeof(char)*STACKSIZE_);
if(!s.base)
{
cout<<"栈创建失败!"<<endl;
exit(-2);
}
s.top=s.base;
s.stacksize=STACKSIZE_;
return s;
}
S InitStack(S s)
{
char ch;
int i=1;
cout<<"输入第"<<i<<"个入栈的元素:"<<endl;
while((ch=cin.get())!=‘\n‘)
{
cin.get();
*(s.top)=ch;
i++;
s.top++;
cout<<"输入第"<<i<<"个入栈元素:"<<endl;
}
return s;
}
int StackLength(S s)
{
char *p;
int length=0;
p=s.base;
if(s.base==NULL)
{
cout<<"栈不存在!"<<endl;
return 0;
}
else
{
while(p!=s.top)
{
length++;
p++;
}
return length;
}
}
S EmptyStack(S s)
{
s.top=s.base;
return s;
}
S DestroyStack(S s)
{
free(s.base);
s.base=NULL;
s.top=NULL;
s.stacksize=0;
return s;
}
S Insert(char ch,S s)
{
if(s.top-s.base>=s.stacksize)
{
s.base=(char *)realloc(s.base,sizeof(char)*(s.stacksize+STACKINCREASEMENT));
if(!s.base)
{
cout<<"内存分配失败!"<<endl;
exit(-2);
}
s.top=s.base+s.stacksize;
s.stacksize+=STACKINCREASEMENT;
}
*s.top++=ch;
return s;
}
S DeleteTopData(S s)
{
if(s.base==s.top)
{
cout<<"栈为空,删除失败!"<<endl;
}
else
{
s.top--;
}
return s;
}
void PrintStackData(S s)
{
char *p;
if(s.base==s.top&&s.base!=NULL)
{
cout<<"空栈无法打印!"<<endl;
}
else if(s.base==NULL)
{
cout<<"栈不存在!无法打印!"<<endl;
}
else
{
p=s.top-1;
while(p!=s.base)
{
cout<<*p<<endl;
p--;
}
cout<<*p<<endl;
}
}
int main()
{
S stack;
char ch;
int choice;
stack=CreateStack();
stack=InitStack(stack);
if(stack.base!=stack.top&&stack.top!=NULL)
cout<<"栈初始化成功!"<<endl;
else
cout<<"创建了空栈!"<<endl;
while(1)
{
system("pause");
system("cls");
cout<<"1.栈的长度"<<endl;
cout<<"2.向栈顶插入元素"<<endl;
cout<<"3.删除栈顶元素"<<endl;
cout<<"4.销毁栈"<<endl;
cout<<"5.清空栈"<<endl;
cout<<"6.打印栈"<<endl;
cout<<"7.退出程序"<<endl;
cout<<"选择操作:";
cin>>choice;
switch(choice)
{
case 1:if(stack.base!=NULL)cout<<"栈长度为:"<<StackLength(stack)<<endl;break;
case 2:cout<<"输入插入元素:";cin>>ch;stack=Insert(ch,stack);break;
case 3:stack=DeleteTopData(stack);break;
case 4:stack=DestroyStack(stack);
cout<<"栈已销毁!"<<endl;break;
case 5:stack=EmptyStack(stack);if(stack.base==stack.top)
cout<<"栈已清空!"<<endl;break;
case 6:PrintStackData(stack);break;
case 7:DestroyStack(stack);exit(0);
}
}
return 0;
}
转载注明出处
顺序栈的实现及基本操作(包含创建,初始化,插入,删除栈顶元素,返回长度,清空,销毁,打印操作)
标签:bsp break end let real exit increase stack free
原文地址:https://www.cnblogs.com/lyj-blogs/p/lyj-blogs-SequenceStack.html