栈的数组实现

Stack.h

#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
#include<assert.h>
#define maxsize 10;
typedef int STDataType; 

// 支持动态增长的栈
typedef int STDataType;
typedef struct Stack 
{    STDataType* myarr;  
int _top;       // 栈顶  
int _capacity;  // 容量 
}Stack;

void StackInit(Stack* ps);
void StackCapacity(Stack* ps);
void Stackprint(Stack *ps);
void StackPush(Stack* ps, STDataType x); 
void StackPop(Stack* ps); 
STDataType StackTop(Stack* ps); 
int StackEmpty(Stack* ps);
int StackSize(Stack* ps);
void TestStack();

Stack.c

#include"Stack.h"
void StackInit(Stack* ps)//创建空数组
{
	assert(ps);
	ps->_capacity = maxsize;
	ps->_top = 0;
	ps->myarr = (STDataType*)malloc(sizeof(STDataType)*ps->_capacity);
	if (ps->myarr == NULL)
		return NULL;
}
void StackCapacity(Stack* ps)//扩容
{
	assert(ps);
	if (ps->_top == ps->_capacity)
	{
		if (ps->myarr == 0)
			ps->_capacity = 2;
		ps->myarr= (STDataType *)realloc(ps->myarr, ps->_capacity*sizeof(STDataType)* 2);
		ps->_capacity = ps->_capacity * 2;

	}
}

void StackPush(Stack* ps, STDataType x)//入栈
{
	assert(ps);
	StackCapacity(ps);
	ps->myarr[ps->_top] = x;
	ps->_top++;
}
void Stackprint(Stack *ps)//打印栈
{
	assert(ps);
	Stack *p = ps;
	for (int i = 0; i < ps->_top; i++)
	{
		printf("%d  ", ps->myarr[i]);

	}printf("\n");
}
void StackPop(Stack* ps)//出栈
{
	assert(ps);
	if (ps->_top == 0)
	{
		printf("栈为空\n");
		return NULL;
	}
	
	ps->_top--;
}
int StackEmpty(Stack* ps)//清空栈
{
	assert(ps);
	ps->_capacity = 0;
	ps->_top = 0;
	free(ps->myarr);
	if (ps->_top == 0)
		printf("栈为空");
}
int StackSize(Stack* ps)//输出栈的大小
{
	assert(ps); 
	
	 printf("栈的长度为%d\n",ps->_top);
}
STDataType StackTop(Stack* ps)
{
	assert(ps);
	if (ps->_top == 0)
	{
		printf("栈为空\n");
		return NULL;
	}
	printf("栈顶的内容%d\n", ps->myarr[ps->_top-1]);
	
}

Test.c

#include"Stack.h"
int main()
{
	Stack ps;
	StackInit(&ps);//创建空数组
	StackPush(&ps, 1);
	StackPush(&ps, 2);
	StackPush(&ps, 5);
	Stackprint(&ps);
	StackPop(&ps);
	
	Stackprint(&ps);
	StackPush(&ps, 9);
	Stackprint(&ps);
	StackSize(&ps);
	StackTop(&ps);
//	Stackprint(&ps);
	//StackEmpty(&ps);

}

发布了24 篇原创文章 · 获赞 4 · 访问量 2623

猜你喜欢

转载自blog.csdn.net/weixin_41548145/article/details/103609851
今日推荐