便于理解的顺序栈操作

内容

实现顺序栈的初始化、入栈、出栈、判空、判满、遍历、取顶

代码

#include"head.h"
typedef int ElemType;
typedef struct
{
	ElemType data[MAXSIZE];
	int top;
}*Stack;

void Init(Stack S)
{
	if (S == NULL)
	{
		printf("内存分配失败\n");
		exit(0);
	}
	S->top = (Stack)malloc(sizeof(Stack));
	S->top = 0;
}
int Empty(Stack S)
{
	if (S->top == 0)
	{
		return TRUE;
	}
	else
		return FALSE;
}
int Full(Stack S)
{
	if (S->top == MAXSIZE-1)
		return TURE;
	else
		return FALSE;
}
void Push(Stack S)
{
	int n;
	int flag = 0;
	if (Full(S) == TURE)
	{
		printf("满栈,无法入栈\n");
	}
	else {
		while (flag == 0)
		{
			printf("请输入入栈元素个数\n");
			scanf("%d", &n);
			if ((n + S->top) < MAXSIZE)
				flag = 1;
			else
				printf("个数溢出,请重新输入\n");
		}
		if (flag == 1)
		{
			for (int i = 0; i < n; i++)
			{
				printf("请输入入栈元素\n");
				int elem;
				scanf("%d", &elem);
				S->data[S->top] = elem;
				S->top++;
			}
		}

	}
}
void Pop(Stack S)
{
	if (Empty(S) == TURE)
		printf("空栈\n");
	printf("元素%d出栈\n", S->data[S->top-1]);
	S->top--;
}
void Read(Stack S)
{
	printf("表长为%d\n", S->top);
	printf("开始遍历\n");
	for (int i = 0; i < S->top; i++)
	{
		printf("%d\n", S->data[i]);
	}
}
void GetTop(Stack S)
{
	if (Empty(S) == TURE)
	{
		printf("栈为空,无法取顶\n");
		exit(0);
	}
	printf("栈顶元素为:%d\n",S->data[S->top-1]);
}
void test()
{
	Stack S = (Stack)malloc(sizeof(Stack));
	Init(S);
	Push(S);
	Read(S);
	GetTop(S);
	Pop(S);
	Read(S);
}
int main()
{
	test();
}

你可能感兴趣的:(栈,新手,c语言,数据结构)