2015-09-16 33 views
0

我试图通过引用比较两个单独链接列表中的节点,而不是值。 我的链表的实现是在通过引用比较链接列表中的节点

struct node{ 
    node(char data):data(data), next(nullptr){} 
    char data; 
    node* next; 
}; 

class slist{ 
    node* head; 
public: 
    slist(node* head):head(head){} 

    node*& getHead(){ 
     return head; 
    } 
    void insert(char item){ 
     node* p = new node(item); 
     if(head == nullptr){ 
      head = p; 
      return; 
     } 
     p->next = head; 
     head = p; 

    } 

这是重载运算符,我用参照两个节点进行比较。

bool operator==(node*& p, node*& q){ 
    if(p->data == q->data) return true; 
    return false; 
} 
    static node* compare(node*& p, node*& q){ 
     if(p == nullptr || q == nullptr) return nullptr; 
     node* current1 = p; 
     node* current2 = q; 

     while(current1 != nullptr){ 
      while(current2 != nullptr){ 
       if(current1 == current2) return current1; 
       current2 = current2->next; 
      } 
      current1 = current1->next; 
     } 
     return nullptr; 

    } 
}; 

驱动程序代码如下:

bool operator==(node*& p, node*& q){ 
     if(p->data == q->data) return true; 
     return false; 
    } 

static node* intersection(node*& p, node*& q){ 
    if(p == nullptr || q == nullptr) return nullptr; 
    node* current1 = p; 
    node* current2 = q; 

    while(current1 != nullptr){ 
     while(current2 != nullptr){ 
      if(current1 == current2) return current1; 
      current2 = current2->next; 
     } 
     current1 = current1->next; 
    } 
    return nullptr; 

} 

,我不断收到如下错误:

error: overloaded 'operator==' must be a binary operator (has 3 parameters) 
    bool operator==(node*& p, node*& q){ 
     ^
+0

我不确定*&实际上是否为您做了任何事情,除了难以理解并且可能会造成潜在的隐患。 *会给你相同的功能。而且他们真的应该是const。 –

回答

0

会员运营商总是this指针作为隐含参数,所以你只需要另一个对象。

bool operator==(node*& q){ 
    if(this->data == q->data) return true; //Could also just have if(data == q->data) but this is a little more explicit 
    return false; 
} 

或者你可以使用你原来的免费功能,但是你将无法使用私有成员,除非你把它声明为好友。