数据结构---栈(数组实现)

本文用C语言描述栈(数组方法实现),以下是源码:

#include "stack_array.h"

PtrToStack CreatStack(uint32_t size)
{
	PtrToStack S;

	if (size < MIN_SIZE)
	{
		printf("Stack size is too small!\r\n");
		return NULL;
	}

	S = (PtrToStack)malloc(sizeof(StackType));
	if (S == NULL)
	{
		printf("Out of space!\r\n");
		return NULL;
	}

	S->Capacity = size;
	S->TopOfStack = EMPTY_TOS;
	S->Element = malloc((sizeof(ElementType))*size);
	if (S->Element == NULL)
	{
		printf("Out of space!\r\n");
		return NULL;
	}

	return S;
}

bool DisposeStack(PtrToStack S)
{
	if (S != NULL)
	{
		free(S->Element);
		free(S);
	}
	return true;
}

bool IsEmpty(PtrToStack S)
{
	return (S->TopOfStack <= EMPTY_TOS);
}
bool IsFull(PtrToStack S)
{
	return (S->TopOfStack >= (S->Capacity-1));
}

bool MakeEmpty(PtrToStack S)
{
	S->TopOfStack = EMPTY_TOS;
	return true;
}

bool Push(PtrToStack S, ElementType X)
{
	if (IsFull(S))
	{
		printf("Stack if full!\r\n");
		return false;
	}

	S->TopOfStack += 1;
	*((S->Element) + (S->TopOfStack)) = X;
	return true;
}

ElementType Top(PtrToStack S)
{
	ElementType WrongRet;
	if (IsEmpty(S))
	{
		memset(&WrongRet, 0, sizeof(ElementType));
		return WrongRet;
	}

	return *(S->Element + S->TopOfStack);
}
bool Pop(PtrToStack S)
{
	if (IsEmpty(S))
	{
		printf("Empty stack!\r\n");
		return false;
	}

	S->TopOfStack--;
	return true;
}

ElementType TopAndPop(PtrToStack S)
{
	ElementType ret;
	if (IsEmpty(S))
	{
		memset(&ret, 0, sizeof(ElementType));
		return ret;
	}
	ret = *(S->Element + S->TopOfStack);
	S->TopOfStack--;
	return ret;
}

bool PrintAllNode(PtrToStack S)
{
	uint32_t ElementCnt = 0;
	int32_t Top = (S->TopOfStack);
	while (Top > EMPTY_TOS)
	{
		printf("No %d element is %c\r\n", ++ElementCnt, (*(S->Element + Top)).Ch);
		Top--;
	}
	printf("********   End   ********\r\n\n");
	return true;
}

#ifndef __STACK_ARRAY_H_
#define __STACK_ARRAY_H_

#include <stdbool.h>
#include <stdint.h>
#include <malloc.h>
#include <stdbool.h>
#include <stdio.h>
#include <memory.h>

#define MIN_SIZE (1)
#define EMPTY_TOS (-1)

typedef union
{
	char Ch;
	uint16_t Index;
	double Value;
} ElementType;

typedef struct
{
	ElementType *Element;
	int32_t TopOfStack;
	int32_t Capacity;
} StackType;

typedef StackType *PtrToStack;

PtrToStack CreatStack(uint32_t size);
bool DisposeStack(PtrToStack S);
bool IsEmpty(PtrToStack S);
bool IsFull(PtrToStack S);
bool MakeEmpty(PtrToStack S);
bool Push(PtrToStack S, ElementType X);
ElementType Top(PtrToStack S);
bool Pop(PtrToStack S);
ElementType TopAndPop(PtrToStack S);
bool PrintAllNode(PtrToStack S);

#endif


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值