冒泡排序链接列表C ++ [英] Bubble sort Linked list C++

查看:120
本文介绍了冒泡排序链接列表C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having problems with this code. I'm pretty sure it's in the swapping.

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

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

"expression must be a modifiable lvalue"

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

Any help is appreciated. Thank you in advance. Here is the code for my bubble-sort algorithm:

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

推荐答案

您做错了.您不能更改函数返回的temp变量的值.

You are doing it wrong. You cannot change the value of temp variable returned by a function.

但是您可以通过这种方式使其工作.

But you can make it work this way..

int& Data() {return data;};

尽管这不是一个好习惯.相反,只需使用您拥有的二传手即可.

though this is not good practise. Instead just use the setter you have..

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

这篇关于冒泡排序链接列表C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆