栈的基本操作 用C语言描述

 #include<malloc.h> /* malloc()等 */
#include<stdio.h> /* EOF(=^Z或F6),NULL */
#include<stdlib.h> /* atoi() */
#include<process.h> /* exit() */
struct StackRecord;
typedef struct StackRecord *Stack;
typedef   char ElementType;
#define EmptyTOS -1
#define MinStackSize 5
 
struct StackRecord
{
int Capacity;
int TopOfStack;
ElementType *Array;
};
void MakeEmpty(Stack S)
{
S->TopOfStack=EmptyTOS;
}
int IsFull(Stack S)
 {  S->TopOfStack== S->Capacity;
 }
int IsEmpty(Stack S)
 { return S->TopOfStack==EmptyTOS;
 }
Stack   CreateStack(int MaxElements )
 {
             Stack S;

/* 1 */        if(MaxElements<MinStackSize)
/* 2 */           {printf("Stack size is too small");
                 exit(0);
                 }
/* 3 */           S=(Stack)malloc(sizeof(struct StackRecord ) );
/* 4 */           if(S==NULL)
/* 5 */             { printf("Out of space!!l");
                        exit(0);
                 }
/* 6 */           S->Array=(ElementType *)malloc(sizeof(ElementType)*MaxElements);
/* 7 */           if(S->Array==NULL)
/* 8 */               { printf("Out of space!!l");
                           exit(0);
                 }
/* 9 */           S->Capacity=MaxElements;
/*10*/           MakeEmpty(S);
/*11*/           return S;
}
void   DisposeStack(Stack S)
{
      if(S!=NULL)
     {
         free(S->Array);
         free(S);
   }
}
void Push(ElementType X, Stack S)
{
     if( IsFull(S) )
{ printf("Full stack");
exit(0);  }
     else
  S ->Array[++S->TopOfStack]=X;//将元素X放入栈中
}
ElementType Top(Stack S)
{
     if(!IsFull(S))
       return S->Array[S-> TopOfStack];//返回栈顶元素
    /* Return value used to avoid warning */
}
void Pop(Stack S)
{
if(IsEmpty(S) )
  { printf("Empty stack");
exit(0);
                }
else
  S->TopOfStack--;
}
ElementType TopAndPop(Stack S )
{
if(!IsEmpty(S) )
   return S->Array[S->TopOfStack--];
 
}
void main(void)
{  
 printf("先输入5,建立一个大小为5的栈;依次元素a,b,c,d,e进栈/n");
 char c1,c2;
    Stack S;
    int i,MAX;
    scanf("%d",&MAX);getchar( );
    S=CreateStack(MAX);//建立一个大小MAX的栈
    for(i=1;i<=MAX;i++)
 {
  scanf("%c",&c1);//通过键盘输入为变量c1赋值
  getchar();
        Push(c1,S);//将c1压入栈中
 } 
    printf("S->TopOfStack:%c/n ",Top(S));  //输出栈顶元素
    Pop(S);//栈顶元素出栈
    for( i=1;i<MAX;i++)
    printf("%c ",TopAndPop(S));// 输出栈序列
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值