c++ - 冒泡排序链表 C++

标签 c++ sorting linked-list bubble-sort

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

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

"expression must be a modifiable lvalue"

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

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;
}

最佳答案

你做错了。您不能更改函数返回的临时变量的值。

但你可以让它以这种方式工作..

int& Data() {return data;};

虽然这不是好的做法。相反,只需使用您拥有的二传手..

curr->Set(nextEl->Data());

关于c++ - 冒泡排序链表 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11570193/

相关文章:

c - 链接列表使我的程序崩溃

c++ - 在 VB.NET 中故意卡住应用程序

C++ std::map 或 std::set - 有效地插入重复项

sorting - 根据他们在 Redis 上的分数对 2(或 N)排序集进行范围搜索的最佳解决方案

iOS 根据浮点值排序数组

javascript - 在递归算法的 return 语句期间我的变量值如何变化?

python - Python 中的引用和值传递

c++ - 将字符串转换为整数数组

c++ - 如何在 DirectX 9 中创建立方体贴图

perl - 如何在Perl中按键对哈希的哈希排序?