c ++:赋值中的非Ivalue

jko*_*jko 1 c++ pointers

嗨,我想制作一个外部单链表.我有一个问题"赋值中的非Ivalue"及其出现在行"this = currP-> next"我试图使它成为currP.next但它也产生错误

#include <cstdlib>
using namespace std;


struct node{
       int data;
       node *next;

       node(int i){
                data = i;
                next = NULL;
                }

       void insert(int position, node &n){
            node *currP = this;
            node *prevP= NULL;      
            for(int counter = 0; counter>=position;counter++, prevP = currP, currP = currP->next){
                    if(counter==position)
                    {
                    n.next  = currP->next;
                    currP->next = &n; 
                                         }                     
                    }

            }

       void add(node &n){
       next = &n;          
                 }
       void deleteNode(int i){
            node *currP = this;
            node *prevP = NULL;

            while(currP!= NULL){
               if(currP->data == i){
                  if(prevP == NULL) 
                      this = currP->next;
                  else{   
                      prevP->next = currP->next;
                  }                      
               }                                                  
               prevP = currP;
               currP = currP->next;
            }
        }
 };
Run Code Online (Sandbox Code Playgroud)

Luc*_*ore 5

An lvalue是一个可以位于等于运算符左侧的变量.这意味着它的价值可以改变.你不能改变this它的值,它只是不允许,因此错误.

您可以按如下方式重写您的函数:

    node* deleteNode(int i){
        if (  this->data == i )
           return this->next;
        else
        {
           if ( this->next )
              this->next = this->next->deleteNode(i);
           else
              return this;
        }
    }
Run Code Online (Sandbox Code Playgroud)

deleteNode()现在将返回一个指向该列表的其余部分和递归算法将与拼接的最后部分,第一部分的开始.它没有经过测试,所以可能需要进行一些调整,但我希望你明白这一点.

  • 取决于您希望该行代码执行的操作 (2认同)
  • @jko - 我明白了,但我建议这是一个很糟糕的问题,正如@JamesKanze所指出的那样.有一个只有一个成员的列表类是合理的:`node head;`并将列表管理操作移到那里.另外:考虑如何表示一个空列表:它是一个NULL节点指针,还是一个魔术_sentinel_节点?......无论如何,这个评论很快就会变得太大了. (2认同)