栈顺序存储方式实现

栈顺序存储方式实现


## 0. 栈结构定义
#include "stdio.h"
#include "stdlib.h"

#define MAXSIZE 20

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int Status; 
typedef int SElemType;

typedef struct SeqStack{
	SElemType data[MAXSIZE];
	// 栈顶指针 
	int top;
}SeqStack;

1. 初始化栈

Status InitStack(SeqStack* stack)
{
	stack->top = -1;
	return OK;
}

2.判断栈是否为空

Status StackEmpty(SeqStack stack)
{
	if ( stack.top == -1 )
		return TRUE;
	else
		return FALSE;
}

3. 压栈操作

Status Push(SeqStack* stack, SElemType e)
{
	if (stack->top >= MAXSIZE -1)
		return ERROR;
	stack->top++;
	stack->data[stack->top] = e;
	return OK;
}

4. 弹栈操作

Status Pop(SeqStack* stack, SElemType* e)
{
	if (stack->top == -1 )
		return ERROR;
	*e = stack->data[stack->top];
	stack->top--;
	return OK;
}

5. 获取栈顶元素

Status GetTop(SeqStack stack, SElemType* e)
{
	if (stack.top == -1)
		return ERROR;
	*e = stack.data[stack.top];
	return OK;
}

6. 获得栈的长度

int StackLength(SeqStack satck)
{
	return satck.top + 1;
}

7. 打印栈元素

Status StackTraverse(SeqStack stack)
{
        int i;
        i=0;
        while(i<=stack.top)
        {
            printf("%d\t",stack.data[stack.top--]);
            
        }
        printf("\n");
        return OK;
} 

8. 清空栈

Status ClearStack(SeqStack* stack)
{
	stack->top = -1;
	return OK;
}

9. 测试

int main(void)
{
	SeqStack stack;
	// 初始化栈
	InitStack(&stack);
	// 向压栈
	Push(&stack,1); 
	Push(&stack,11); 
	Push(&stack,111);
	printf("The length of Stack is:%d\n",StackLength(stack));
	int value;
	Pop(&stack,&value);
	printf("弹出的元素为:%d\n",value);
	StackTraverse(stack);
	
	return 0;
}
发布了30 篇原创文章 · 获赞 58 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/annjeff/article/details/101679119