栈的基本操作C语言实现 数据结构

运行的过程,首先入栈四个元素,打印,接下来4入栈,再次打印,下面打印栈顶元素,最后栈顶元素出栈,再次打印

#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 100 
#define STACKINCREMENT 10 
typedef struct {
       int *base;
	   int *top;  
	   int stacksize;  
}SqStack; 

//初始化栈 
int InitStack(SqStack &S) { 
    S.base = (int*)malloc(STACK_INIT_SIZE * sizeof(int));  
    if (!S.base) {
	exit(-1); 
}
    S.top = S.base; 
    S.stacksize = STACK_INIT_SIZE; 
    return 1; 
} // InitStack

//获得栈顶元素 
int GetTop(SqStack S,int &e) { 
    if (S.top == S.base) 
	{
	       return 0; 
     }
    e = *(S.top-1); 
    return 1; 
} // GetTop 

//入栈 
int Push (SqStack &S, int e) { 
    if (S.top - S.base >= S.stacksize) { 
       S.base = (int*)realloc(S.base, 
                      (S.stacksize + STACKINCREMENT) * sizeof(int));  
       if (!S.base)
       {
       	exit (-1); 
	   } 
       S.top = S.base + S.stacksize; 
       S.stacksize += STACKINCREMENT; 
	   } 
    * S.top ++ = e;         
	 return 1; 
} // Push 

//出栈
int Pop (SqStack &S,int &e) { 
    if (S.top == S.base) 
	{
	return 0; 
}
    e = *--S.top; 
    return 1; 
} // Pop 

//打印栈
void print(SqStack S) {
	for(int i=1;i<=S.top-S.base;i++){
		printf("%d \n",*(S.top-i));
	}
}
int main(){
	SqStack s;
	InitStack(s);
	printf("7,1,2,3依次入栈\n");
	Push(s,7);
	Push(s,1);
	Push(s,2);
	Push(s,3);
	print(s);
	printf("4入栈打印全部\n");
	Push(s,4);
	print(s);
	int e; 
	GetTop(s,e);
	printf("打印栈顶元素\n");
	printf("%d \n",e);
	printf("出栈后打印\n");
	Pop(s,e);
	print(s);
	
	
	
	
}






 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值