首先说一下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);
/*
用户补充
*/
}