我遇到了这段代码的问题。我很确定这是在交换。
行: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;
}
答案 0 :(得分:1)
你做错了。您无法更改函数返回的临时变量的值。
但是你可以这样工作..
int& Data() {return data;};
虽然这不是好习惯。相反,只需使用你拥有的setter ..
curr->Set(nextEl->Data());
答案 1 :(得分:0)
声明
curr->Data() = nextEl.Data();
永远不会工作,你试图为函数的返回值赋值。我不知道你如何定义Node,但你可能意味着像
curr->Data = nextEl.Data();
即,为Node的成员分配内容。
答案 2 :(得分:0)
更改
curr ->Data() = nextEl ->Data();
nextEl ->Data() = temp;
到
curr->Set(nextEl ->Data());
nextEl->Set(temp);