[英]C++ Stack by Array Implementation
我想发生的是pushFront(int)函数执行此操作:
bool stack::pushFront( const int n ) { items[++top] = n; // where top is the top of the stack return true; // only return true when the push is successful }
items是对象“ item”的结构类型。 看一看:
class stack { stack(int capacity); ~stack(void); ... private: int maxSize; // is for the item stack int top; // is the top of the stack struct item { int n; }; item *items;
我已经将ctor定义为堆栈类对象和dtor,如下所示:
stack::stack(int capacity) { items = new item[capacity]; if ( items == NULL ) { throw "Cannot Allocoate Sufficient Memmory"; exit(1); } maxSize = capacity; top = -1; } stack::~stack(void) { delete [] items; items = NULL; maxSize = 0; top = -1; }
是的,对我来说,主要问题是items [++ top] = n; 声明。 我一直在尝试寻找解决方法,如下所示:
bool stack::pushFront(const int n) { int *a = new int[maxSize]; a[++top] = n; return true; }
但是我无法拖动(+)'a'数组来查看那些实际的数组元素...这就是我希望发生的事情。
我想要的是语句items [++ top] = n; 上班..
您不能将int值分配给项目,因为您尚未告诉编译器该怎么做。
您需要为将int作为参数的项目编写构造函数或operator =,或者使用
items[++top].n = n;
看来您已经定义了固定大小的堆栈。 您应检查添加到堆栈中的大小不超过该大小。 要使用pushFront,您只需要复制数组中的数据即可为要修改的第0个元素腾出空间:
bool stack::push(const int n)
{
if ( top >= capacity-1 ) return false;
items[++top].n = n
}
bool stack::pushFront(const int n)
{
if ( top >= capacity-1 ) return false;
bcopy( items, items+1, top+1 );
items[0].n = n;
return true;
}
bool stack::pushFront( const int n )
{
if(top == maxSize-1)
return false;
items[++top].n = n; // where top is the top of the stack
return true; // only return true when the push is successful
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.