顺序栈

//SeqStack.h

#ifndef _SEQSTACK_H_
#define _SEQSTACK_H_
#include <stdio.h>


#define MAXSIZE		10
#define INCREASE	3

typedef int ElementType;
typedef enum
{
	false_,
	true_
}bool_;


typedef struct SeqStack
{
	ElementType *Base;
	int			 top;			//栈顶指针
	int			 capacity;		//容量
}SeqStack, *pSeqStack;

bool_ initSeqStack(SeqStack *st);
bool_ increase(SeqStack *st);
bool_ push(SeqStack *st, ElementType e);
void pop(SeqStack *st);
void show(SeqStack st);
bool_ isFull(SeqStack st);
bool_ isEmpty(SeqStack st);
int length(SeqStack st);
bool_ getTop(SeqStack st, ElementType *e);
void clear(SeqStack *st);
void destroy(SeqStack *st);

#endif //_SEQSTACK_H_



//SeqStack.c

#include "SeqStack.h"
#include <stdlib.h>

bool_ initSeqStack(SeqStack *st)
{
	st->Base = (ElementType *)malloc(MAXSIZE * sizeof(ElementType));
	if( NULL == st->Base )
	{
		printf("申请内存失败\n");
		return false_;
	}
	st->capacity = MAXSIZE;
	st->top = 0;
	
	return true_;
}

bool_ increase(SeqStack *st)
{
	ElementType *newBase = (ElementType *)realloc(st->Base, sizeof(ElementType) * (MAXSIZE + INCREASE));
	if( NULL == newBase )
		return false_;

	st->Base = newBase;
	st->capacity += INCREASE;

	return true_;
}

bool_ push(SeqStack *st, ElementType e)
{
	if( isFull(*st) && !increase(st) )
	{
		printf("栈已满, %d入栈失败\n", e);
		return false_;
	}

	st->Base[st->top++] = e;
	return true_;
}

void pop(SeqStack *st)
{
	if( isEmpty(*st) )
	{
		printf("栈已空\n");
		return false_;
	}
	st->top--;
}

void show(SeqStack st)
{
	for(int i = st.top - 1; i >= 0; i--)
		printf("%d\n", st.Base[i]);
}

bool_ isFull(SeqStack st)
{
	return st.top >= st.capacity;
}

bool_ isEmpty(SeqStack st)
{
	return 0 == st.top;
}

int length(SeqStack st)
{
	return st.top;
}

bool_ getTop(SeqStack st, ElementType *e)
{
	if( isEmpty(st) )
	{
		printf("栈为空\n");
		return false_;
	}
	*e = st.Base[st.top - 1];	
	return true_;
}

void clear(SeqStack *st)
{
	st->top = 0;
}

void destroy(SeqStack *st)
{
	free(st->Base);
	st->top = 0;
	st->capacity = 0;
}




//main.c

#include "SeqStack.h"
#include <Stdlib.h>

int main(int argc, char **argv)
{
	SeqStack st;
	ElementType e = 0;
	initSeqStack(&st);

	printf("入栈操作\n");
	for(int i = 0; i < 13; i++)
		push(&st, i);
	printf("栈大小为%d\n", length(st));

	printf("显示栈中元素\n");
	show(st);
	getTop(st, &e);
	printf("栈顶元素是%d\n", e);

	printf("出栈操作\n");
	for( int i = 0; i < 15; i++)
		pop(&st);

	printf("显示栈中元素\n");
	show(st);

	clear(&st);
	destroy(&st);

	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值