C语言实现堆栈

来源:互联网 发布:淘宝企业店铺可靠吗 编辑:程序博客网 时间:2024/04/25 20:58
//抱歉没有多少注释,是以前大二的程序直接拿来就用的,以后会多多注意的
#define OVERFLOW -1
#define ERROR -2
#define OK 1
#define NULL 0
#define STACK_INT_SIZE 100
#define STACKINCREMENT 10
#include <stdio.h>
typedef struct{
char *base;
char *top;
int stacksize;
}SqStack;
int CreatStack(SqStack *S)
{
 (*S).base=(char *)malloc(STACK_INT_SIZE*sizeof(char));
 if(!(*S).base) return ERROR;
 (*S).top=(*S).base;
 (*S).stacksize=STACK_INT_SIZE;
 return OK;
}
int StackLength(SqStack S)
{SqStack p;
 int length=0;
 p=S;
 while(p.base!=p.top)
   {p.top--;
    length++;
   }
 return length;
}
int GetTop(SqStack S,char *e)
{if(S.base==S.top)  return ERROR;
 *e=*(S.top-1);
 return OK;
}
int Push(SqStack *S,char e)
{
 if((*S).top-(*S).base>=(*S).stacksize){
 (*S).base=(char *)realloc((*S).base,((*S).stacksize+STACKINCREMENT)*sizeof(char));
 if((*S).base)  exit(OVERFLOW);
 (*S).top=(*S).base+(*S).stacksize;
 (*S).stacksize+=STACKINCREMENT;
 }
 *((*S).top)++=e;
 return OK;
}
int Pop(SqStack *S,char *e)
{if((*S).top==(*S).base)
   return ERROR;
 *e=*--(*S).top;
 return OK;
}
int DestroyStack(SqStack *S)
{char *p;
 while((*S).top!=(*S).base)
 {p=(*S).top;
  --(*S).top;
  free(p);
 }
 return OK;
}
int ClearStack(SqStack *S)
{int length,n;
 if(S->base==S->top) return OK;
 else
   {while(S->base!=S->top)
      *(--S->top)=NULL;
   }
  return OK;
}
int Print(SqStack *S)
{
 char *p;
 for(p=S->top-1;p>=S->base;p--)
   printf("%c",*p);
 printf("/n");
 return OK;
}
int StackEmpty(SqStack S)
{if(S.top==S.base)
  return OK;
 else
  return  NULL;
}
main()
{SqStack *stack,*stack1,*stack2;
 char *c,e;
 stack=(SqStack *)malloc(sizeof(SqStack));
 stack1=(SqStack *)malloc(sizeof(SqStack));
 stack2=(SqStack *)malloc(sizeof(SqStack));
 c=(char *)malloc(sizeof(char));
 clrscr();
 CreatStack(stack);
 CreatStack(stack1);
 CreatStack(stack2);
 printf("Have created a stack,the length of it is %d/n",StackLength(*stack));
 if(!StackEmpty(*stack))
  printf("Stack is not empty!/n");
 else
  printf("Stack is empty!/n");
 printf("Please input chars(End with '!'):/n");
 while((e=getchar())!='!')
   Push(stack,e);
 printf("Print the stack:");
 Print(stack);
 printf("The length of stack is%d/n",StackLength(*stack));
 while(!StackEmpty(*stack)) {Pop(stack,c); Push(stack1,*c);}
 while(!StackEmpty(*stack1)) {Pop(stack1,c); Push(stack2,*c);}
 while(!StackEmpty(*stack2)) {Pop(stack2,c); Push(stack,*c);}
 printf("Reverse print the stackis:");
 Print(stack);
 DestroyStack(stack);
 DestroyStack(stack1);
 DestroyStack(stack2);
 getch();
}