簡體   English   中英

冒泡排序鏈接列表C ++

[英]Bubble sort Linked list C++

我在使用此代碼時遇到問題。 我很確定它正在交換中。

該行: 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;
}

你做錯了。 您不能更改函數返回的temp變量的值。

但是您可以通過這種方式使其工作..

int& Data() {return data;};

盡管這不是一個好習慣。 而是使用您擁有的二傳手。

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

該聲明

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

將永遠無法工作,您正在嘗試為函數的返回值分配某些內容。 我不知道您如何定義Node,但是您可能會說類似

curr->Data = nextEl.Data();

即,將一些東西分配給Node的成員。

更改

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM