栈的顺序存储和入栈出栈操作
参考《大话数据结构》P92~94——栈的顺序存储结构。
举个简单的例子:
代码和解释如下(VS2012测试通过):
1 #include <iostream> 2 using namespace std; 3 4 #define MAXSIZE 4 5 //本例中栈满共4个元素 6 7 //栈的顺序存储结构 8 typedef struct 9 { 10 char data[MAXSIZE];//栈的顺序存储结构用数组实现 11 int top;//栈顶元素的数组下标(书上说用于栈顶的指针,注意不是指针) 12 }SqStack; 13 14 //栈的初始化,分配内存空间 15 SqStack *InitSqStack(SqStack *s) 16 { 17 s=new SqStack; 18 s->top=-1;//初始化为空栈 19 return s; 20 } 21 22 //进栈操作push 23 void Push(SqStack *s,char e) 24 { 25 if(s->top==MAXSIZE-1)//栈满的条件 26 { 27 cout<<"stack is full,push error"<<endl; 28 return;//如果栈满,就不进行元素的进栈操作 29 } 30 s->top++;//如果栈未满,首先将当前的top+1 31 s->data[s->top]=e;//把新插入的元素赋值给栈顶空间(本质就是数组的赋值操作) 32 cout<<e<<" "<<"push ok"<<endl;//输出提示,插入成功 33 return; 34 } 35 36 //出栈操作pop 37 void Pop(SqStack *s,char *e)//把调用者需要被修改的变量的地址传入该函数,调用者需要修改的变量也会被修改 38 { 39 if(s->top==-1)//栈空的条件 40 { 41 cout<<"stack is empty"<<endl; 42 return ;//如果栈空,就不进行元素的出栈操作,直接返回 43 } 44 *e=s->data[s->top];//把要出栈的元素赋给*e 45 //指针e获得了调用者需要被修改的变量的地址,操作*e操作就是操作调用者的变量 46 s->top--;//元素出栈之后,把当前的top-1 47 cout<<"pop ok"<<" ";//输出提示,删除成功 48 return; 49 } 50 51 int main() 52 { 53 SqStack *p=NULL;//定义一个指向栈结构的指针p 54 p=InitSqStack(p);//初始化p 55 56 //入栈 57 Push(p,'A');//插入A 58 Push(p,'B');//插入B 59 Push(p,'C');//插入C 60 Push(p,'D');//插入D 61 Push(p,'E');//栈满,不能再插入 62 63 //出栈 64 char e; 65 char *EleOut=&e; 66 Pop(p,EleOut);//D出栈,传入e的地址 67 cout<<e<<endl; 68 Pop(p,EleOut);//C出栈,传入e的地址 69 cout<<e<<endl; 70 Pop(p,EleOut);//B出栈,传入e的地址 71 cout<<e<<endl; 72 Pop(p,EleOut);//A出栈,传入e的地址 73 cout<<e<<endl; 74 Pop(p,EleOut);//栈空,出栈失败 75 }
运行结果:
-------------------------------------------------
原创博客 转载请注明出处http://www.cnblogs.com/hslzju
-------------------------------------------------