- /*
- * sqstack.cpp
- *
- * Created on: 2012-5-12
- * Author: awind
- */
- #include <iostream>
- #include<memory.h>
- #define STACK_INIT_SIZE 100 //存储空间初始分配量
- #define STACKINCREMENT 10 //存储空间分配增量
- using namespace std;
- typedef struct
- {
- int *base;
- int *top;
- int stackSize;
- }SqStack;
- bool InitStack( SqStack &s )
- {
- s.base = new int[STACK_INIT_SIZE];
- if( !s.base ) //如果该栈非空,,表示存储失败,则将其置为空 ?
- return false;
- s.top = s.base;
- s.stackSize = STACK_INIT_SIZE;
- return true;
- }
- bool GetTop( SqStack s, int &e )
- {
- if( s.top == s.base )
- {
- cout<<"the stack is empty!"<<endl;
- return false;
- }
- e = *( s.top - 1 );
- return true;
- }
- bool Push( SqStack &s, int e )
- {
- if( s.top - s.base >= s.stackSize ) //栈满,则追加存储空间
- {
- int *pNewBase = new int[ ( s.stackSize + STACKINCREMENT ) ];
- memcpy( pNewBase, s.base, sizeof( int ) * s.stackSize );//1为搬迁位置,2为搬迁前位置,
- //3为搬迁的数量大小。
- delete []s.base; //删除原来的存储空间
- s.base = pNewBase; //将栈地和栈顶重新赋新值
- s.top = s.base + s.stackSize; //栈顶指向增加的第一块空间
- s.stackSize += STACKINCREMENT;
- }
- *s.top++ = e;
- return true;
- }
- bool Pop( SqStack &s, int &e )
- {
- if( s.top == s.base )
- return false;
- e = *--s.top;
- return true;
- }
- bool StackEmpty( SqStack s )
- {
- if( s.top == s.base )
- return true;
- else
- return false;
- }
- int main()
- {
- int n,e;
- SqStack stack;
- InitStack(stack);
- cout<<"input the num you want to push: ";
- while(cin>>n)
- {
- Push(stack,n);
- }
- while( !StackEmpty( stack ) )
- {
- Pop( stack, e );
- cout<<e<<endl;
- }
- }
STL中vector实现: stack.h
- /*
- * stack.h
- *
- * Created on: 2012-5-12
- * Author: awind
- */
- #ifndef STACKV_H_
- #define STACKV_H_
- #include <iostream>
- #include <cstdlib>
- #include <vector>
- #define STACK_INIT_SIZE 10
- using namespace std;
- class Stack
- {
- public:
- Stack();
- bool push(int element);
- bool isEmpty() const;
- int pop();
- bool isfull();
- void getmem();
- int size();
- private:
- vector<int> stack;
- };
- #endif /* STACKV_H_ */
stack.cpp
- /*
- * stack.cpp
- *
- * Created on: 2012-5-12
- * Author: awind
- */
- #include "stackv.h"
- using namespace std;
- Stack::Stack()
- {
- stack.reserve(STACK_INIT_SIZE); //初始化设置栈的容量
- }
- bool Stack::isEmpty() const
- {
- return stack.empty();
- }
- bool Stack::isfull()
- {
- return stack.size()==stack.max_size();
- }
- bool Stack::push(int element)
- {
- if(isfull()){ //栈满则增加栈的容量
- stack.reserve(stack.size()+STACK_INIT_SIZE);
- }
- stack.push_back(element);
- return true;
- }
- int Stack::pop()
- {
- if(isEmpty())
- return false;
- int element=stack.back();
- stack.pop_back();
- return element;
- }
- void Stack::getmem()
- {
- if(isEmpty())
- return;
- for(size_t i=0;i!=stack.size();++i)
- {
- cout<<stack[i]<<" ";
- }
- cout<<endl;
- }
- int Stack::size()
- {
- return stack.size();
- }
- int main()
- {
- Stack s;
- cout<<s.size()<<endl;
- for(int i=0;i<10;i++)
- {
- s.push(i);
- }
- cout<<s.size()<<endl;
- s.getmem();
- return 0;
- }