|
发表于 2015-1-8 20:33:21
|
显示全部楼层
- //2014.10.02 顺序栈的实现方式
- #include<iostream>
- #include<math.h>
- #include"assert.h"
- using namespace std;
- #define INCREMENT_SIZE 2
- typedef struct STACK
- {
- int stacksize;
- int* pstop; //栈顶指针p表示指针s表示栈
- int* psbottom;
- }STACK;
- void init_stack(STACK& s)
- {
-
- s.stacksize = INCREMENT_SIZE;
- //注意加1的原因:s.psbottom不存放数据本身要占据一个字节的空间
- s.pstop = s.psbottom =(int*)malloc(sizeof(int)*(s.stacksize+1));
- if(NULL == s.pstop)
- {
- cout<<"为栈分配存储空间失败";
- return;
- }
-
- }
- bool push(STACK& s,int val)
- {
-
- int k = s.pstop-s.psbottom;
- if((s.pstop-s.psbottom)>=s.stacksize)
- {
- //注意加1的原因:s.psbottom不存放数据本身要占据一个字节的空间
- s.psbottom = (int*)realloc(s.psbottom ,sizeof(int)*(s.stacksize+INCREMENT_SIZE+1));
- if(NULL == s.psbottom)
- {
- cout<<"栈已满,为将要压栈的元素分配内存失败"<<endl;
- return false;
- }
- s.pstop = s.psbottom+s.stacksize;
- s.stacksize+=INCREMENT_SIZE;
- }
- s.pstop++;
- *s.pstop = val;
-
- return true;
- }
- bool pop(STACK& s,int& val)
- {
- if(s.psbottom == s.pstop)
- {
- cout<<"栈为空出栈失败"<<endl;
- return false;
- }
- val = *s.pstop--;
- return true;
- }
- void dis_stack(STACK& s)
- {
- if(s.pstop == s.psbottom)
- {
- cout<<"栈为空"<<endl;
- return ;
- }
-
- int* p = s.pstop ;
- while(p != s.psbottom)
- {
- cout<<*p<<endl;
- p--;
- }
- }
- bool get_top(STACK&s, int& val)
- {
- if(s.psbottom == s.pstop)
- {
- cout<<"栈为空"<<endl;
- return false;
- }
- val = *s.pstop;
- return true;
- }
- STACK stack;
- int main(void)
- {
- init_stack(stack);
- push(stack,23);
- push(stack,78);
- push(stack,26);
- push(stack,90);
- push(stack,45);
- push(stack,45);
- push(stack,78);
- push(stack,123);
- dis_stack(stack);
- int val = 0;
- cout<<endl;
- pop(stack,val);
- cout<<val<<endl;
- cout<<endl;
- pop(stack,val);
- cout<<val<<endl;
- cout<<endl;
- dis_stack(stack);
- int top_val;
- get_top(stack,top_val);
- cout<<endl;
- cout<<top_val<<endl;
- return 0;
- }
复制代码 |
|