本文共 2345 字,大约阅读时间需要 7 分钟。
#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(); } 转载地址:http://mdpci.baihongyu.com/