我写的这种方法认为不好,有好的写法希望大神能指导指导。
CStock & CStock::operator =(const CStock & otherStock)
{
CStock tempStock;
Item * copyElement = otherStock.p_Top;
//将栈otherStock的元素出栈,依次进入tempStock内,元素的位置顺序和otherStock相反;
while(copyElement)
{
tempStock.push(copyElement->data);
copyElement = copyElement->p_next;
}
copyElement = tempStock.p_Top;
//将tempStock的元素出栈,依次进入此栈内,元素位置和otherStock同样。
while(copyElement)
{
push(copyElement->data);
copyElement = copyElement->p_next;
}
return *this;
}
//进栈操作
void CStock::push(elemType x)
{
Item * pushElement = new Item;
pushElement->data = x;
if(!p_Top)//假设栈为空时
{
p_Top = pushElement;
pushElement->p_next = NULL;
}
else //若栈不为空时
{
pushElement->p_next = p_Top;
p_Top = pushElement;
}
}
//出栈操作,若栈不为空。数据有形?x带至主调函数,出栈失败函数返回false;
bool CStock::pop(elemType &x)
{
if(!p_Top)
{
return false;
}
x = p_Top->data;
p_Top = p_Top->p_next;
return true;
}
//推断栈是否为空
bool CStock::isEmpty() const
{
return p_Top == NULL;
}
//清空栈,使栈置为空栈
void CStock::clear()
{
Item * deleteElement;
while(p_Top)
{
deleteElement = p_Top;
p_Top = p_Top->p_next;
delete deleteElement;
}
}
//获得栈的大小
int CStock::size() const
{
int length = 0;
Item *temp = p_Top;
while(temp && ++length)
{
temp = temp->p_next;
}
return length;
}
//打印栈内元素
void CStock::print() const
{
int count = 0;
Item * temp = p_Top;
while(temp && ++count)
{
cout << temp->data << " ";
if(count % 5 == 0)
cout << endl;
temp = temp->p_next;
}
}
//析构函数,提供对指针成员的释放,默认的会出现潜在问题
CStock::~CStock(void)
{
Item * deleteElement;
while(p_Top)
{
deleteElement = p_Top;
p_Top = p_Top->p_next;
delete deleteElement;
}
}