C++用类对堆栈的操作,请写详细点
论文问答
1
class STACK{
int *const elems; //申请内存用于存放栈的元素
const int max; //栈能存放的最大元素个数
int pos; //栈实际已有元素个数,栈空时pos=0;
public:
STACK(int m); //初始化栈:最多m个元素
STACK(const STACK&s); //用栈s拷贝初始化栈
int size ( ) const; //返回栈的最大元素个数max
int howMany ( ) const; //返回栈的实际元素个数pos
STACK& push(int e); //将e入栈,并返回栈
STACK& pop(int &e); //出栈到e,并返回栈
STACK& assign(const STACK&s); //赋s给栈,并返回被赋值的栈
void print( ) const; //打印栈
~STACK( ); //销毁栈
};
怎么写函数声明,谢谢了
-
函数声明不都有了么?你该写函数实现啦。
参考代码
/** •<!-- •File : stack.h •Author : fancy •Email : fancydeepin@yeah.net •Date : 2013-02-03 •--!> */ #include #include #include #define Element char #define INIT_SIZE 10 #define INCREMENT_SIZE INIT_SIZE / 2 typedef struct TStack { Element *base; Element *top; int size; } *Stack; //栈的构造器,创建空栈 void stackConstructor(Stack &stack){ stack->base = (Element *)malloc(INIT_SIZE * sizeof(Element)); if(!stack->base){ printf("\n为栈分配内存空间失败!\n"); exit(0); } stack->top = stack->base; //空栈 top == base stack->size = INIT_SIZE; } //是否为空栈 bool isEmpty(Stack stack){ if(stack->top == stack->base){ return true; } return false; } //压栈 bool push(Stack &stack, Element e){ if(stack->top - stack->base >= stack->size){ //栈满 stack->base = (Element *)realloc(stack->base, (stack->size + INCREMENT_SIZE) * sizeof(Element)); if(!stack->base){ printf("\n为栈扩展内存空间失败!\n"); return false; } stack->top = stack->base + stack->size; stack->size += INCREMENT_SIZE; } *stack->top++ = e; return true; } //弹栈 Element pop(Stack stack){ if(isEmpty(stack)){ printf("\n栈为空,弹栈操作失败!\n"); return ' '; } return *--stack->top; } /** •<!-- •File : Stack.cpp •Author : fancy •Email : fancydeepin@yeah.net •Date : 2013-02-03 •--!> */ #include "stack.h" int main() { Stack stack; stackConstructor(stack); push(stack, 'f'); push(stack, 'a'); push(stack, 'n'); push(stack, 'c'); push(stack, 'y'); printf("%c", pop(stack)); printf("%c", pop(stack)); printf("%c", pop(stack)); printf("%c", pop(stack)); printf("%c", pop(stack)); //output[result]: ycnaf return 0; }
-
class STACK{ public: STACK(int m); //初始化栈:最多m个元素 STACK(const STACK&s); //用栈s拷贝初始化栈 int size ( ) const; //返回栈的最大元素个数max int howMany ( ) const; //返回栈的实际元素个数pos STACK& push(int e); //将e入栈,并返回栈 STACK& pop(int &e); //出栈到e,并返回栈 STACK& assign(const STACK&s); //赋s给栈,并返回被赋值的栈 void print( ) const; //打印栈 ~STACK( ); //销毁栈 private: int *const elems; //申请内存用于存放栈的元素 const int max; //栈能存放的最大元素个数 int pos; //栈实际已有元素个数,栈空时pos=0; }
发表回复