用内存动态分配定义栈的顺序存储结构

本文详细介绍了如何使用C语言创建一个动态大小的栈,包括栈的初始化、入栈、出栈、读取栈顶元素、计算栈中元素个数以及打印栈的内容。
摘要由CSDN通过智能技术生成
#include<stdio.h>
#include<stdlib.h>
#define MAXSTACKSIZE 100
#define INTISTACKSIZE 10
//用内存动态分配定义栈的顺序存储结构 
typedef struct
{
	int *base;
	int *top;
	int stacksize;
 }SqStack;
 
 //构造一个空栈初始化 
 int InitStack(SqStack*S)
 {
 	S->base=(int*)malloc(MAXSTACKSIZE*sizeof(int));
 	if(!S->base)
 	return 0;
 	S->top=S->base;
 	S->stacksize=MAXSTACKSIZE;
 	return 1;
  } 
  //入栈
  int Push(SqStack*S,int e)
  {
  	//判断栈满,并为他增加分配内存空间 
  	if(S->top==S->base+S->stacksize)
  	{
  		S->base=(int*)realloc(S->base,(S->stacksize+INTISTACKSIZE)*sizeof(int));
		  if(!S->base)
		  return 0;
		  S->top=S->base+S->stacksize;
		  S->stacksize=S->stacksize+INTISTACKSIZE; 
	  }
	  *(S->top)=e;
	  S->top=S->top+1; 
	  return 1;
   } 
   //退栈
   int Pop(SqStack*S,int *e)
   {
   	  if(S->top==S->base)
   	  return 0;
   	  S->top=S->top-1;
   	  *e=*(S->top);
   	  return 1;
	} 
	//读取栈顶元素
	int GetStackTop(SqStack S,int *e)
	{
		if(S.top==S.base)
		return 1;
		*e=*(S.top-1);
		return *e;
	 } 
	 //求栈中元素个数
	 int StackLength(SqStack S)
	 {
	 	return S.top-S.base;
	  } 
	  //输出栈元素
	void PrintStack(SqStack *S)
    {
    if (S->top == S->base)
    {
        printf("栈为空");
    }
    else
    {
        int *p = S->base;
        while (p < S->top)
        {
            printf("%d ", *p);
            p++;
        }
        printf("\n");
    }
    } 
  int main()
  {
  	  SqStack S;
  	  int *e;
  	  InitStack(&S);
  	  Push(&S,1);
  	  Push(&S,2);
  	  Push(&S,3);
  	  PrintStack(&S); 
  	  Pop(&S,&e);
  	  PrintStack(&S);
  	  printf("%d\n",GetStackTop(S,&e));
  	  printf("%d",StackLength(S));
  	  return 0;
  }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值