链栈的基本操作(动态分配空间)

#define STACK_INIT_SIZE 10//the orgin size

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>// if false,break all the things
typedef struct sqStack
{
	int *base;  //base point 
	int *top;	//top point
	int stack_Size;
}sqStack;

//1.traverse all the stack
void print_stack(sqStack*s)
{
	assert(s); //if s is true
	int *num = s->base;//using the point 
	if (s->base == s->top) {
		printf("this is a empty stack!");
	}
	for (num; num != s->top; num++)
	{
		printf("the num is %2d", *num);
		printf("\n");
	}
}
//init_Stack
sqStack*init_Stack(sqStack*s) {
	s = (sqStack*)malloc(sizeof(sqStack));//assign the room
	if (!s)
	{
		exit(0);
	}
	s->base = (int*)malloc(STACK_INIT_SIZE * sizeof(int));//assign the num
	s->top = s->base;
	s->stack_Size = STACK_INIT_SIZE;
	printf("Init the stack sucessfully!\n");
	return s;
}
//Free_stack
int Free_stack(sqStack*s) {
	if (!s)
	{
		printf("Stack is no need to free");
		return 0;
	}
	else
	{
		free(s->base);
		free(s);
		return 1;
	}
}
//push data to stack
int push_stack(sqStack*s, int e) {
	assert(s);
	//(if the stack is full ,assign the room automaticly)
	if (s->top - s->base >= s->stack_Size) //the stack is full
	{
		s->base = (int*)realloc(s->base, (s->stack_Size + 2)*sizeof(int));//the int is 2 byte
		if (!s->base)
		{
			printf("realloc false\n");
			return 0;
		}
		s->top = s->base + s->stack_Size;
		s->stack_Size += 2;
	}
	*(s->top) = e;
	++(s->top);
	return 1;
}

int	pop_stack(sqStack*s)
{
	assert(s);
	if (s->base == s->top) {
		printf("it is a empty stack\n");
		return 0;
	}
	printf("the pop data is %2d\n",*((s->top)-1));
	--(s->top);
	return 1;
}
void main()
{
	int i;
	sqStack *s;
	s = init_Stack(&s);
	for (i = 0; i < 20; i++)
	{
		int num = rand() % 100;
		push_stack(s, num);
	}
	print_stack(s);
	printf("*************************************begin to pop stack***************************************\n");
	pop_stack(s);
	print_stack(s);
	Free_stack(s);
	system("pause");

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值