C语言数据结构栈的操作集

#include<stdio.h>
#include<malloc.h>
#define OVERFLOW -2
#define OK 1
#define ERROR -1
#define FALSE 0
#define M 100
#define m 10
typedef int ElemType;
typedef struct{
ElemType *base;
ElemType *top;
int stacksize;
}Sqstack;


int  createstack(Sqstack &S,ElemType i)
{
int j;
S.base=(ElemType*)malloc(M*sizeof(ElemType));
    
S.top=S.base;
S.stacksize=M;
    for(j=0;j<i;j++)
{
++S.top;
scanf("%d",S.top-1);
}
return 1;
}


int  print(Sqstack &S)
{
   if(S.base==NULL)
  return ERROR;
   if(S.top==S.base)
  printf("栈中没有元素。。。。\n");
   ElemType *p;
   p=S.top;
   printf("表中元素若出栈顺序为:\n");
   while(p>S.base)
   {
  p--;
  printf("%3d",*p);
   }
   return 0;
}


void lengthstack(Sqstack &S)
{
int e;
printf("栈的长度是多少:\n");
if(S.top==S.base)
printf("没有了  你还让我查!");
else 
e=S.top-S.base;
printf("%d",e);

}
void  gettopstack(Sqstack &S)
{   
   int e;
   if(S.top==S.base)
printf("没有了  你还让我找 哼!");
   else
     e=*(S.top-1);
   printf("找到了大兄弟,栈顶元素是:\n");
   printf("%d",e);
}
void  deletestack(Sqstack &S)
{
int e;
 if(S.top==S.base)
printf("没有了  你还让我删除 哼!");
 else
 {
S.top--;
e=*S.top;
printf("删除栈顶元素为%d:\n",e);
 }
}
void pushstack(Sqstack &S, ElemType e)  
{  

    if (S.top - S.base >= M)  
    {  
        S.base = (ElemType *)realloc(S.base, (S.stacksize + m) * sizeof(ElemType));  
        if (!S.base)  
        {  
           printf("大兄弟 分配失败啊!");
        }  
        S.top = S.base + m;//栈底地址可能改变,重新定位栈顶元素  
        S.stacksize = S.stacksize + m;  
    }  
    *S.top = e;  
    S.top++;    
}  


int main()
{
Sqstack s;
int i,choice,e;
printf("输入1是创建栈并遍历其中的数据:\n输入2是求出栈的长度\n输入3是求出栈顶元素\n输入4是删除栈顶元素并遍历\n输入5是插入一个元素\n ************正在等待用户输入************\n");
while(scanf("%d",&choice)!=EOF)
{
if(choice==1)
{
printf("请输入先创建几个数的栈:\n");
scanf("%d",&i);
createstack(s,i);
print(s);
}

if(choice==2)
{
 lengthstack(s);
}




if(choice==3)
{
gettopstack(s);
}
if(choice==4)
{
deletestack(s);
print(s);
}
if(choice==5)
{
printf("输入要插进的元素:\n");
scanf("%d",&e);
pushstack(s,e);
print(s);
}




printf("\n**********正在等待用户输入**************\n");
}
          
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值