数据结构day7栈-顺序栈的实现

  用指针比用数组好,这样用户可以自己指定空间的大小,有参与感。

 

 全部代码:

main.c

#include <stdio.h>
#include <string.h>
#include "sqstack.h"


int main(int argc, char *argv[])
{
	sqstack *s;
	int i;

	s = stack_create(100);

	if(s == NULL)
		return -1;

	stack_push(s,100);
	stack_push(s,90);
	stack_push(s,80);
	stack_push(s,70);
	stack_push(s,60);
	
	for(i = 0; i <= s->top; i++)//显示栈中的元素
	{
	printf("%d\n", s->data[i]);
	}

	while(!stack_empty(s)) {
		printf("pop : %d\n",stack_pop(s));
	}

	stack_free(s);


	return 0;
}

sqstack.c

#include <stdio.h>
#include <stdlib.h>
#include "sqstack.h"
#include <string.h>

/* 要创建一个结构体的栈,和一个放数据的栈  */
sqstack * stack_create(int len){
	sqstack *s;

	if((s = (sqstack *)malloc(sizeof(sqstack))) == NULL) {
		printf("malloc sqstack failed\n");
		return NULL;

	}

	if(((s->data) = (data_t *)malloc(len * sizeof(data_t))) == NULL) {

		printf("malloc data failed\n");
		return NULL;
	}

	memset(s->data, 0, len * sizeof(data_t));
	s->maxlen = len;
	s->top = -1;
	return s;


}
int stack_push(sqstack *s, data_t value){
	if(s == NULL) {
		printf("s is NULL\n");
		return -1;

	}

	if(s->top == s->maxlen -1) {
		printf("stack is full\n");
	return -1;
	}

	s->top ++;
	s->data[s->top] = value;
	return 0;

}
/* 1-empty  */
int stack_empty(sqstack *s){
	if(s == NULL) {
		printf("s is NULL\n ");
		return -1;
	}
	return (s->top == -1 ? 1 : 0);


}
/* 1-full  */
int stack_full(sqstack *s){
	if(s == NULL) {
		printf("s is NULL\n");
		return -1;
	}

	return (s->top == s->maxlen - 1 ? 1 : 0);

}
data_t stack_pop(sqstack *s){
	s->top--;
	return (s->data[s->top+1]);

}

//显示top的值
data_t stack_top(sqstack *s){
	return (s->data[s->top]);

}


int stack_clear(sqstack *s){
	if(s == NULL)
	{
		printf("s is NULL\n");
		return -1;
	}
	
	s->top = -1;
	return 0;

}


//有几个malloc就有几个free

int stack_free(sqstack *s){
	if(s == NULL)
	{
		printf("s is NULL\n");
		return -1;
	}	
	if(s->data != NULL)//开辟栈可能失败
	{
		free(s->data);
	}
	free(s);
	return 0;
}


sqstack.h

typedef int data_t;

typedef	struct{
	data_t *data;
	int maxlen;
	int top;

}sqstack;


sqstack * stack_create(int len);
int stack_push(sqstack *s, data_t value);
int stack_empty(sqstack *s);
int stack_full(sqstack *s);
data_t stack_pop(sqstack *s);
data_t stack_top(sqstack *s);
int stack_clear(sqstack *s);
int stack_free(sqstack *s);


运行结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Aurora Smith

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值