C++ 实现顺序栈

#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <iostream>
#include <stack>
#define maxSize 100
using namespace std;

/*
Created by HarvestWu on 2018/5/4.
*/

//顺序栈定义
typedef struct
{
	int data[maxSize];	//存放栈中元素
	int top;		//栈顶“指针”
}SqStack;			//顺序栈定义

//顺序栈初始化
void initStack(SqStack &st);
//顺序栈判空
int isEmpty(SqStack st);
//顺序栈进栈
int push(SqStack &st,int x);
//顺序栈出栈
int pop(SqStack &st, int &x);
int main()
{
	SqStack st;
	int x;
	initStack(st);

	if (isEmpty(st))
		printf("栈空\n");
	else printf("栈非空\n");

	if (push(st,5))
		printf("入栈成功\n");
	else printf("栈满,不能入栈\n");

	if (isEmpty(st))
		printf("栈空\n");
	else printf("栈非空\n");

	if (pop(st, x))
		printf("出栈成功,出栈元素为:%d\n",x);
	else printf("栈空,不能出栈\n");
	return 0;
}

void initStack(SqStack &st)
{
	st.top = -1;//设置-1表示为空(能利用下标0的空间)
}

int isEmpty(SqStack st)
{
	if (st.top == -1)
		return 1;
	else
		return 0;
}

int push(SqStack &st, int x)
{
	if (st.top == maxSize - 1)	//栈满,不能入栈
		return 0;
	st.data[++st.top] = x;		//移动“指针”,然后入栈
	return 1;
}

int pop(SqStack &st, int &x)
{
	if (st.top == -1)		//栈空,不能出栈
		return 0;
	x = st.data[st.top--];		//取出元素,然后移动“指针”	
	return 1;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值