0

我在使用此代码时遇到问题。我很确定它在交换中。

该行:curr->Data() = nextEl.Data()给我以下错误:

“表达式必须是可修改的左值”

任何帮助表示赞赏。先感谢您。这是我的冒泡排序算法的代码:

class Node
{
private:
    int data;
    Node* next;
public:
    Node() {};
    void Set(int d) { data = d;};
    void NextNum(Node* n) { next = n;};
    int Data() {return data;};
    Node* Next() {return next;};
};

class LinkedList
{
    Node *head;
public:
    LinkedList() {head = NULL;};
    virtual ~LinkedList() {};
    void Print();
    void AddToTail(int data);
    void SortNodes();
};


void LinkedList::SortNodes() 
{
Node *curr = head;
Node *nextEl = curr ->Next();
Node *temp = NULL;

if(curr == NULL)
    cout <<"There is nothing to sort..."<< endl;
else if(curr -> Next() == NULL)
    cout << curr -> Data() << " - " << "NULL" << endl;
else
{
    for(bool swap = true; swap;)
    {
        swap = false;
        for(curr; curr != NULL; curr = curr ->Next())
        {
            if(curr ->Data() > nextEl ->Data())
            {
                temp = curr ->Data();
                curr ->Data() = nextEl ->Data();          
                nextEl ->Data() = temp;
                swap = true;
            }
            nextEl = nextEl ->Next();
        }
    }
}
curr = head;
do
{
    cout << curr -> Data() << " - ";
    curr = curr -> Next();
}
while ( curr != NULL);
cout <<"NULL"<< endl;
}
4

3 回答 3

1

你这样做是不对的。您不能更改函数返回的临时变量的值。

但是你可以让它这样工作..

int& Data() {return data;};

虽然这不是一个好习惯。相反,只需使用您拥有的二传手..

curr->Set(nextEl->Data());
于 2012-07-19T22:31:19.867 回答
0

该声明

curr->Data() = nextEl.Data();

永远不会工作,你正试图为函数的返回值分配一些东西。我不知道您是如何定义 Node 的,但您的意思可能类似于

curr->Data = nextEl.Data();

即,将某些内容分配给 Node 的成员。

于 2012-07-19T22:27:38.013 回答
0

改变

curr ->Data() = nextEl ->Data(); 
nextEl ->Data() = temp;

curr->Set(nextEl ->Data()); 
nextEl->Set(temp);
于 2012-07-19T23:42:14.007 回答