栈的基本接口

Stack.h

#ifndef _STACK_H_
#define _STACK_H_

#include<stdio.h>
#include<Windows.h>

typedef int STDataType;

typedef struct Stack
{
	STDataType a[20];
	int top; //栈顶
	int capacity; //容量
}Stack;

void StackInit(Stack* ps, int size);
void StackDestory(Stack* ps);

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


#endif /*_STACK_H_*/

Stack.c

#include"Stack.h"

void StackInit(Stack* ps, int size)
{
	ps->capacity = size;
	ps->top = -1;
}

void StackDestory(Stack* ps)
{
	ps->top = -1;
	ps->capacity = 0;
}

void StackPush(Stack* ps, STDataType x)
{
	//判满
	if (ps->top == ps->capacity - 1)
	{
		printf("栈满\n");
		return;
	}
	ps->top++;
	ps->a[ps->top] = x;
}

STDataType StackPop(Stack* ps)
{
	//判空
	if (StackEmpty(ps))
	{
		printf("栈空\n");
		return 0;
	}
	return ps->a[ps->top--];
}

STDataType StackTop(Stack* ps)
{
	//判空
	if (StackEmpty(ps))
	{
		printf("栈空\n");
		return 0;
	}
	return ps->a[ps->top];
}

int StackEmpty(Stack* ps)
{
	if (ps->top == -1)
	{
		return 1;
	}
	return 0;
}

int StackSize(Stack* ps)
{
	int size = 0;
	if (!StackEmpty(ps))
	{
		while (ps->top != 0)
		{
			ps->top--;
			size++;
		}
	}
	return size;
}

main.c

#include"Stack.h"

int main()
{
	Stack ps;

	StackInit(&ps, 100);

	StackPush(&ps, 5);
	StackPush(&ps, 4);
	StackPush(&ps, 3);
	StackPush(&ps, 2);
	StackPush(&ps, 1);

	printf("%d\n", StackPop(&ps));
	printf("%d\n", StackPop(&ps));
	printf("%d\n", StackPop(&ps));
	printf("%d\n", StackPop(&ps));
	printf("%d\n", StackPop(&ps));
//	printf("%d\n", StackPop(&ps));



	StackDestory(&ps);
	system("pause");
	return 0;
}
发布了67 篇原创文章 · 获赞 15 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_43746320/article/details/97526919