实现顺序栈各种基本运算算法

本文介绍了一种基于数组实现的顺序栈数据结构,并详细展示了其核心操作:初始化、销毁、判断空栈、入栈、出栈及获取栈顶元素等。通过C语言实现,提供了完整的代码示例和运行流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//SeqStack.h
typedef char ElemType;
#define MaxSize 100

typedef struct 
{
	ElemType data[MaxSize];
	int top;
}SeqStack;

// 初始化栈
extern void InitStack(SeqStack *&s);

// 销毁栈
extern void DestroyStack(SeqStack *&s);

// 判断栈是否为空
extern int StackEmpty(SeqStack *s);

// 入栈
extern void PushStack(SeqStack *&s, ElemType e); 
// 出栈
extern ElemType PopStack(SeqStack *&s);
// 取栈顶元素
extern ElemType GetTop(SeqStack *&s, ElemType &e);


//SeqStack.cpp

//SeqStack.cpp
#include<malloc.h>
#include<stdio.h>
#include"SeqStack.h"

// 初始化栈
void InitStack(SeqStack *&s)
{
	s = (SeqStack *)malloc(sizeof(SeqStack));
	s->top = -1;
}

// 销毁栈
void DestroyStack(SeqStack *&s)
{
	free(s);
}

// 判断栈是否为空
int StackEmpty(SeqStack *s)
{
	if ( s->top == -1 )
		return 1;
	else
		return 0;
}

// 入栈
void PushStack(SeqStack *&s, ElemType e)
{
	if ( s->top == MaxSize - 1 )
		printf("Stack full\n");
	else
	{
		s->top++;
		s->data[s->top] = e;
	}
}

// 出栈
ElemType PopStack(SeqStack *&s )
{
	ElemType e;
	if ( s->top == -1 )
	{
		printf("Stack empty!\n");
		return NULL;
	}
	else
	{
		e = s->data[s->top];
		s->top--;

		return e;
	}
}

// 取栈顶元素
ElemType GetTop(SeqStack *&s, ElemType &e)
{
	if ( s->top == -1 )
	{
		printf("Stack Empyt!\n");
		return NULL;
	}
	else
	{
		e = s->data[s->top];
		return e;
	}
}

//main.cpp

//main.c
#include<malloc.h>
#include<stdio.h>
#include"SeqStack.h"

int main()
{
	SeqStack *s;
	ElemType e;

	s = (SeqStack *)malloc(sizeof(SeqStack));
	

	printf("\n栈s的基本运算如下:\n");

	printf("[1]初始化栈s: \n");
	InitStack(s);

	printf("[2]栈为 %s \n",(StackEmpty(s) ? "空":"非空"));

	printf("\n[3]依次入栈元素: a, b, c, d, e\n");
	PushStack(s,'a');
	PushStack(s,'b');
	PushStack(s,'c');
	PushStack(s,'d');
	PushStack(s,'e');

	

	printf("[4]栈为 %s \n",(StackEmpty(s) ? "空":"非空"));

	printf("\n[5]出栈序列: ");
	while(!StackEmpty(s))
	{
		printf("%c ",PopStack(s));
	}
	
	printf("\n[6]栈为 %s \n",(StackEmpty(s) ? "空":"非空"));

	printf("[7]释放栈!\n");
	DestroyStack(s);

	return 0;
}





                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值