Bubble sort Linked list C++

这一生的挚爱 提交于 2019-12-12 01:16:36

问题


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

The line: curr->Data() = nextEl.Data() gives me the following error:

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

回答1:


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());



回答2:


The statement

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

will never work, you are trying to assign something to the return value of a function. I don't know how you defined Node, but you probably meant something like

curr->Data = nextEl.Data();

i.e., assign something to a member of Node.




回答3:


change

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

to

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


来源:https://stackoverflow.com/questions/11570193/bubble-sort-linked-list-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!