如果不知道具体需要建多大的站,构造函数怎么写
如果不知道具体需要建多大的站,构造函数怎么写
如果不知道具体需要建多大的站,构造函数怎么写
2016-10-29
根据老师写了一个整个的程序,这个是申请物理空间的,因为物理空间很大一般不会不足,符合你的问题,所以可以按需要取多少大小。
不是很规范,有所不足互相学习哈
#include<iostream> using namespace std; #define elemtype char struct node { elemtype data; node *last; node *next; //新定义的结点的默认构造函数 node(const elemtype data = 0,node *last = NULL,node *next = NULL) { this->data = data; this->last = last; this->next = next; } ~node() { data = 0; last = next = NULL; } }; class stack{ private: node *base; //栈底 node *top; //栈顶 int size; //栈的实际大小 public: stack() { //申请一个哨兵结点作为栈底,哨兵的data没有意义 //如果申请物理空间失败,抛出异常 if (!(base = new node())) { cout << "内存不足!"; //throw ... } top = base; size = 0; } ~stack() { node *p=base,*q=NULL; while(p) { q = p; p = p->next; delete q; } } bool isfull() { //尝试申请一个node,如果可以申请说明未满 node *p=new node; if (!p) { return true; } else { delete p; return false; } } bool isempty() { return !size; //也可以写成 return top == base; } void push(const elemtype &c) { if (isfull()) { cout << "满了"; //throw .. } node *p = new node(c); top->next = p; p->last = top; top = p; ++size; } elemtype pop() { if (isempty()) { cout << "空了"; //theow .. } elemtype x = top->data; node *p = top; top = p->last; top->next = NULL; delete p; --size; return x; } //遍历函数,默认从栈底到栈顶 void traverse(bool isfrombottom = true) { node *p; if (isfrombottom) { p = base->next; while (p) { cout << p->data; p = p->next; } cout<<endl; } else { p = top; while (p != base) { cout << p->data; p = p->last; } cout<<endl; } } int lenth() { return size; } void clearStack() { node *p = base->next,*q; while (p) { q = p; p = p->next; delete q; } top = base; size = 0; base->next = NULL; } }; int main(void) { stack *s = new stack(); if (s->isempty()) cout<<"栈为空"<<endl; cout << s->lenth()<<endl; s->push('h'); s->push('e'); s->push('l'); s->push('l'); s->push('o'); cout << s->lenth()<<endl; s->traverse(); s->traverse(false); s->clearStack(); cout << s->lenth()<<endl; cout <<endl; s->push('a'); s->traverse(); s->pop(); s->traverse(); //测试是不是能二次入栈 s->push('a'); s->traverse(); s->pop(); s->traverse(); //因为内存物理空间蛮大的,所以一般栈满的情况不会出现 在此不做测试 //if (s->isfull()) //cout<<"栈为满"<<endl; s->clearStack(); //最后这句话送给大家 s->push('H'); s->push('a'); s->push('p'); s->push('p'); s->push('y'); s->push(' '); s->push('C'); s->push('h'); s->push('r'); s->push('i'); s->push('s'); s->push('t'); s->push('m'); s->push('a'); s->push('s'); s->push('!'); s->traverse(); delete s; return 0; }
举报