顺序栈

 

首先说一下C++中的引用吧,什么是引用?

例如 

int a=&b,b;

你说这样行不行,答案是否定的,必须要初始化时候

int &a,b;
a=b;//error,编译器报错

引用换句话说就是给变量起一个别名,有什么好处呢,举个栗子!

比如我们需要改变一个变量a的值,下面这一种很明显很失败!

void  ceshi(int num)
{
    num=10;
}
void main()
{
    int a=1;
    ceshi(a);//输出a=1
}

我们只需要使用引用加一个&就OK了,如下:

void  ceshi(int &num)
{
    num=10;
}
void main()
{
    int a=1;
    ceshi(a);//输出a=10
}

言归正传,顺序栈

贴代码:初始化,删除,清空,进栈,出栈

//栈
//顺序性
//链结
#include <malloc.h>
#include <iostream>
using namespace  std;
#define MAX_SIZE   10
#define increase   2
typedef  bool  status;
typedef  int   type;
typedef struct 
{
	type *base;
	type *top;
	int stacksize;
}tyust;


//栈初始化
void stack_init(tyust &s)
{
	s.base=(type*)malloc(MAX_SIZE*sizeof(type));
	if(!s.base)
	{
		cout<<"ERROR";
	}
	s.top=s.base;
	s.stacksize=MAX_SIZE;//头部应该不存放数据!!
}
//销毁栈
void  destroy(tyust &s)
{
	free(s.base);
	s.top=s.base=NULL;
	s.stacksize=0;
}

//清除栈
void clear(tyust &s)
{
	s.top=s.base;
}

//判断栈状态
status isempty(tyust &s)
{
	if(s.base==s.top)
	{
		return true;
	}else return false;
}
//返回栈长度
int  length(tyust &s)
{
	return s.top-s.base;
}

//把栈的top给e
status gettop(tyust s,type &e)
{
	if(s.top>s.base)//非空
	{
		e=*(s.top-1);
		return true;
	}else return false;

}
//压入元素
void push(tyust &s,type e)
{
	if((s.top-s.base)==s.stacksize)//栈满
	{
		s.base=(type*)realloc(s.base,(s.stacksize+increase)*sizeof(type));//重新分配
		if(!s.base)
			cout<<"Realloc  ERROR!!";
		s.top=s.base+s.stacksize;
		s.stacksize+=increase;
	}
	*s.top=e;
	s.top++;
	//*(s.top)++=e;
}
//弹出元素
void pop(tyust &s,type &e)
{
	if(s.top==s.base)cout<<"Empty!!";
	e=*(--s.top);
}

void ceshi(int &num)
{
	num=10;
}
void main()
{
	tyust S;
	stack_init(S);
        /*
          用户补充
        */	
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值