【数据结构】栈的实现

文章目录

    • Stack.h
    • Stack.c
    • Test.c

Stack.h

#ifndef  __STACK_H__
#define  __STACK_H__



#include 
#include 
#include 
#include 

typedef int  DataType;

typedef  struct Stack
{
	DataType* _a;
	size_t  _top;
	size_t  _capacity;
}Stack;



void StackInit(Stack* s);
void StackPush(Stack* s, DataType x);
void StackPop(Stack* s);
DataType StackTop(Stack* s);
size_t StackSize(Stack* s);
int StackEmpty(Stack* s);
void StackDestory(Stack* s);
void text();




#endif

Stack.c

#include "Stack.h"


void StackInit(Stack* s)
{
	assert(s != NULL);
	s->_a = (DataType*)malloc(sizeof(DataType)* 10);
	s->_top = 0;
	s->_capacity = 10;
}
void StackDestory(Stack* s)
{
	assert(s);
	s->_a = NULL;
	s->_top = 0;
	s->_capacity = 0;
	free(s);
	s = NULL;
}
void StackPush(Stack* s, DataType x)
{
	DataType* cur;
	assert(s);
	if (s->_top == s->_capacity)
	{
		cur = (DataType*)realloc(s->_a, sizeof(DataType)* 2 * (s->_capacity));
		if (cur != NULL)
		{
			s->_a = cur;
		}
		s->_capacity *= 2;
	}
	s->_a[s->_top++] = x;
}
void StackPop(Stack* s)
{
	assert(s);
	assert(s->_top > 0);
	s->_top--;
}
DataType StackTop(Stack* s)
{
	assert(s);
	assert(s->_top > 0);
	return s->_a[s->_top - 1];

}
size_t StackSize(Stack* s)
{
	assert(s);
	return s->_top++;
}
int StackEmpty(Stack* s)
{
	assert(s);
	return s->_top == 0 ? 0 : 1;
}





Test.c

#include "Stack.h"

void text()
{
	Stack s;
	StackInit(&s);
	StackPush(&s, 1);
	StackPush(&s, 3);
	StackPush(&s, 5);
	//printf("Stack's size : %d \n", StackSize(&s));
	//printf("Stack's top : %d \n", StackTop(&s));
	//printf("Stack Is Empty Stack?: %d \n", StackEmpty(&s));
	//StackPop(&s);
	//printf("Stack's size : %d \n", StackSize(&s));
	while (StackEmpty(&s) != 0)
	{
		printf("%d ", StackTop(&s));
		StackPop(&s);
	}
	printf("\n");
}






int main()
{
	text();
	system("pause");
	return 0;
}


你可能感兴趣的:(神兵利剑)