【问题标题】:Problem with insertion at a certain point in linked list with inherited functions in C++在 C++ 中使用继承函数在链表中的某个点插入问题
【发布时间】:2019-08-15 01:03:59
【问题描述】:

我试图在链表中的某个位置插入一个数字。但是我无法正常访问下一个指针,因为它是私有成员,并且必须使用 getNext 函数。我不确定如何用这个函数分配下一个指针,因为它给了我错误。

#pragma once

class IntListNode {
public:
    IntListNode(int e, IntListNode *nextptr): 
        elem(e), next(nextptr) { }
    int &getElement() {return elem;}
    IntListNode *getNext() {return next;}
private:
    int elem;                   // linked list element value
    IntListNode *next;          // next item in the list
};

这是我尝试过的代码,但我不断收到错误。

void IntegerList::AddAtPosition(int num, int placement)
{
    IntListNode* temp1 = head;

    IntListNode* temp2 = head;

    temp1->getElement() = num;

    if (placement == 0)
    {
        head = temp1;
    }
    else
    {
        for (int i = 0; i < placement - 2; i++)
        {
            temp2 = temp2->getNext();
        }
        temp1->getNext() = temp2->getNext();
        temp2->getNext() = temp1;
        //THe Lines getting errors
    }

}

错误信息:

E0137 "表达式必须是可修改的左值"

【问题讨论】:

标签: c++ list class pointers linked-list


【解决方案1】:

将您的 getNext() 方法更改为:IntListNode*&amp; getNext() {return next;}

IntListNode *getNext() 版本将返回 next 成员的值,但不是它的地址,因此该行不可修改:tempX-&gt;getNext() = tempY;


编辑

根据 OP 提到的限制/条件,我能想到的唯一方法是:

*temp1 = IntListNode(temp1->getElement(), temp2->getNext());
*temp2 = IntListNode(temp2->getElement(), temp1);

【讨论】:

  • 那行代码是给我提供的,所以我必须在不修改的情况下解决它。
  • 由于代码错误,我更新了答案。现在已经修好了。虽然我没有测试运行它。
  • 我无法更改方法,因为它是问题中给出的代码。有没有办法在不改变 getNext 方法的情况下访问下一个指针?
  • 你不能像setNext(IntListNode* newNextPtr)一样在IntListNode中添加方法吗?似乎根据给定的类修改next 的唯一方法是通过构造函数方法。
猜你喜欢
  • 2014-02-11
  • 1970-01-01
  • 1970-01-01
  • 2020-05-11
  • 2020-09-07
  • 2012-12-22
  • 1970-01-01
  • 2011-07-17
  • 1970-01-01
相关资源
最近更新 更多