再学C的数据结构---顺序栈

SeqStack.h

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <malloc.h>

typedef int Elemtype;


#define STACK_INIT_SIZE 8

#define STACK_INC_SIZE 2

typedef struct SeqStack
{
	Elemtype *base;
	int capacity;
	int top;
}SeqStack;

void InitStack(SeqStack* pst);
void Push(SeqStack* pst, const Elemtype x);
bool IsFull(const SeqStack* pst);
bool IsEmpty(const SeqStack* pst);
void Show_Stack(const SeqStack* pst);
void Pop(SeqStack* pst);
bool GetTop(SeqStack* pst, Elemtype* v);
int Length(const SeqStack* pst);
void Clear(SeqStack* pst);
void Destroy(SeqStack* pst);
bool Inc(SeqStack* pst);

SeqStack.cpp

#include "SeqStack.h"


void InitStack(SeqStack* pst)
{
	assert(pst != NULL);
	pst->base = (Elemtype*)malloc(sizeof(Elemtype)*STACK_INIT_SIZE);
	assert(pst->base != NULL);
	pst->capacity = STACK_INIT_SIZE;
	pst->top = 0;
}



bool IsFull(const SeqStack* pst)
{
	return pst->top >= pst->capacity;
}



bool IsEmpty(const SeqStack* pst)
{
	return pst->top == 0;
}



void Push(SeqStack* pst, const Elemtype x)
{
	assert(pst != NULL);
	if (IsFull(pst) && !Inc(pst))
	{
		printf("Stack is Full or Inc error\n");
		return;
	}
	pst->base[pst->top++] = x;
}



void Show_Stack(const SeqStack* pst)
{
	assert(pst != NULL);
	if (IsEmpty(pst))
	{
		return;
	}

	for (int i = pst->top - 1; i >=0 ; --i)
	{
		printf("%d  ", pst->base[i]);
	}
	printf("\n");
}



void Pop(SeqStack* pst)
{
	assert(pst != NULL);
	if (IsEmpty(pst))
	{
		printf("Stack is Empty\n");
	}
	--pst->top;
}


//获取栈顶元素不出栈
bool GetTop(const SeqStack* pst, Elemtype* v)
{
	if (IsEmpty(pst))
	{
		printf("Stack is Empty\n");
		return false;
	}

	*v = pst->base[pst->top - 1];
	return true;
}


int Length(const SeqStack* pst)
{
	return pst->top;
}



void Clear(SeqStack* pst)
{
	assert(pst != NULL);
	pst->top = 0;
}



void Destroy(SeqStack* pst)
{
	assert(pst != NULL);
	free(pst->base);
	pst->base = NULL;
	pst->capacity = pst->top = 0;
}



bool Inc(SeqStack* pst)
{
	assert(pst != NULL);
	Elemtype* newdata = (Elemtype*)realloc(pst->base, sizeof(Elemtype)*pst->capacity*STACK_INC_SIZE);
	if (newdata == NULL)
	{
		return false;
	}
	pst->base = newdata;
	pst->capacity *= STACK_INC_SIZE;
	return true;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值