栈的相关操作

来源:互联网 发布:阿里云费用如何提现 编辑:程序博客网 时间:2024/05/20 16:35

/*****************************************************************************************
**Flie:   stack.c
@@Author:  Freeking
##Created:  Sep 15th 2009
&&Description: 关于栈的操作,包括初始化一个栈,进栈,出栈,判断栈是否为空.取得栈顶,清空栈,
    销毁栈等操作.
*****************************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10

typedef struct {
int *base;
int *top;
int stacksize;
}SqStack;

//初始化一个栈,其大小为100
void InitStack(SqStack *S)
{
 S->base = (int*)malloc(STACK_INIT_SIZE * sizeof(int));
 if(!S->base)
 {
 exit(0);
 }

 S->top = S->base;
 S->stacksize =STACK_INIT_SIZE;
}

//判断栈是否为空
int IsEmpty(SqStack *S)
{
 if(S->top = S->base)
 {
  printf("栈为空!/n");
 }
 return 1;
}
//判断栈是否满
int IsFull(SqStack *S)
{
 if(*(S->top) = STACK_INIT_SIZE)
 {
  printf("栈为空!/n");
 }
 return 1;
}
//往栈中压入元素
void Push(SqStack *S,int e)
{
 int *newbase;
 if(S->top - S->base == S->stacksize)
 {
 newbase=(int *)realloc(S->base,(S->stacksize+STACKINCREMENT)*sizeof(int));
 if(!newbase)
  exit(0);
 S->base = newbase;
 S->top = S->base + S->stacksize;
 S->stacksize +=STACKINCREMENT;
 }
 * (S->top++)=e;//* S->top=e; S->top++;

}

//将栈中元素取出
int Pop(SqStack *S,int e)

 if(S->top == S->base)
  return -1;//S->top ->base 临时变量,此时已是随机值
 e =*(--S->top);
 return e;
}
//将栈顶元素取出
int GetTop(SqStack *S,int e)

 if(S->top == S->base)
  return -1;//S->top ->base 临时变量,此时已是随机值
 e =*(S->top-1);
 return e;
}
main()
{
 char c;
 int i = 0;
 SqStack a;
 InitStack(&a);
 char b[10] = {'a', 'b','c','d','e','f','g','h','i','j'};
 for(; i<10; i++)
 {
  Push(&a,b[i]);
 }
 for(i=0; i<10; i++)
 {
  c = Pop(&a,c);
  printf("%c/n", c);
 }
}

原创粉丝点击