链表C ++的等式运算符

时间:2014-03-16 22:32:47

标签: c++ list linked-list equality singly-linked-list

我正在尝试创建链接列表类,但我无法确定如何使用operator ==(相等运算符)检查两个列表的相等性。我将如何浏览每个节点并检查它们中的元素在各自的位置是否相等?

bool List::operator==(const List& list2) const {
    if(mySize != list2.mySize){
        return false;
    }
    if(myFirst == list2.myFirst){
        if(myFirst == NULL){
            return true;
        }

        Node * nPtr1 = myFirst;
        Node * nPtr2 = list2.myFirst;
        while(nPtr1 != NULL){
            //what can I do here to check the equality of each element in both lists?

        }
    }
}

2 个答案:

答案 0 :(得分:4)

根据你的代码,myFirst是一个指针,所以以下是错误的:

if(myFirst == list2.myFirst)

除非节点等于另一个节点,否则它是相同的节点(指针方式)。

当列表为空时,您有一个特殊情况:

if(myFirst == nullptr && list2.myFirst == nullptr)
{
    return true;
}

那将是空案例。

否则,您可以正常使用,如果您的项目(节点)可以简单地进行比较,您可以这样做:

p = myFirst;
q = list2.myFirst;
while(p != nullptr)
{
    if(*p != *q)  // this is what you're asking about, right?
    {
        return false;
    }
    p = p->next; // not too sure how you have a Node separated from the List
    q = q->next; // and check next/previous items...
}

return true;

请注意,如果节点只有相同的指针才能相等,则比较变为:

    if(p != q) // this is a test of pointers instead of objects

P.S。有人提到使用递归算法。这是一个想法,从概念上来说它很棒。但是,在现实世界中使用它时,你会注意到它可能(更慢)。它必须非常大量地使用堆栈,并且使用非常大的列表,它可能会破坏您的软件。

答案 1 :(得分:0)

while(nPtr1 != NULL){
       if(nPtr1 != nPtr2){
          return false;
       }
       nPtr1=nPtr1->next;
       nPtr2=nPtr2->next;
}
return true;

但是这是检查两个列表是否相同的方法(nPtr1nPtr2指向同一个列表)。如果您真的想按内容比较列表,则必须比较以下内容:

if(nPtr1->content != nPtr2->content)

并且还会更改您的第一个指针检查:

if(myFirst->content == list.myFirst->content)
相关问题