我在为堆栈类编写 operator==
函数时遇到了很多麻烦,我似乎无法理解逻辑。目前我有:
template<class myType>
bool linkedStack<myType>::operator==(const linkedStack<myType>& op)
{
linkedStack<myType> stackA, stackB;
bool res = false;
stackA.copyStack(this);
stackB.copyStack(op);
while(!stackA.isStackEmpty() && !stackB.isStackEmpty())
{
if (stackA.peek() == stackB.peek()) {
stackA.pop();
stackB.pop();
if (stackA.isStackEmpty() && stackB.isStackEmpty())
res = true;
} else
res = false;
}
return res;
}
问题是我无法将当前类堆栈复制到 stackA 中,因为 this
是一个 const 指针,而我的 copyStack 会喷出编译器错误。必须有一个更简单的解决方案,有人可以指出我正确的方向吗?谢谢!
编辑:我的代码的修改部分:
template<class myType>
bool linkedStack<myType>::operator==(const linkedStack<myType>& op)
{
nodeType<myType> *current, *opcurrent;
current = stackTop;
opcurrent = op.stackTop;
while(current != NULL && opcurrent != NULL)
{
if (current->info != opcurrent->info) {
return false;
}
current = current->link;
opcurrent = opcurrent->link;
}
return true;
}
最佳答案
一旦发现不同,就不需要遍历所有堆栈,此时可以直接返回false。
while(!stackA.isStackEmpty() && !stackB.isStackEmpty())
{
if (stackA.peek() == stackB.peek()) {
stackA.pop();
stackB.pop();
} else
return false;
}
return stackA.isStackEmpty() && stackB.isStackEmpty();
更一般地说,如果您在类内部进行操作,您也可以直接使用类的内部数据,而不是制作拷贝(这将导致堆栈保存的所有数据的拷贝作为出色地)。您应该使用几个指针来跟踪内部列表。这段代码可以很容易地从上面的代码中推导出来,它应该给出如下内容:
node *a_ptr = head_ptr;
node *b_ptr = op.head_ptr;
while(!(a_ptr == tail || b_ptr == tail)
{
if (a_ptr->data == b_ptr->data) {
a_ptr = a_ptr->next;
b_ptr = b_ptr->next;
} else
return false;
}
return (a_ptr == tail && b_ptr == tail);
取决于您的实现细节。
关于c++ - 为单链栈写一个 operator==,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16205709/