2012-07-19 157 views
0

我遇到了這段代碼的問題。我很確定它正在交換。泡沫排序鏈接列表C++

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

告訴你,即使不包括你說行代碼導致錯誤。 – 2012-07-19 22:30:22

+0

是的,這是因爲我試圖修復它,但是這種類型的行會在第二個嵌套for循環中的if語句中進行交換。 – philr 2012-07-19 23:24:23

+0

可能重複的[如何使用冒泡排序對鏈表進行排序?](http://stackoverflow.com/questions/19522121/how-to-sort-a-linked-list-using-bubble-sort) – malat 2015-02-12 15:00:40

回答

1

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

但是你可以把它以這種方式工作..

int& Data() {return data;}; 

雖然這不是好的做法。相反,只需使用你的setter ..

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

我只是試過這個,它給了我錯誤,因爲「curr」它給了我「表達式必須是可修改的左值」,對於「nextEL」它給了我「表達式必須具有類類型」 – philr 2012-07-19 23:25:28

+0

您是否添加了'&'符號如圖所示?無論如何,第二種形式應該仍然有效。 – vidit 2012-07-19 23:42:50

+0

是的,我做了,謝謝,我現在沒有錯誤!但我認爲我的循環是錯誤的...我得到一個.exe問題 – philr 2012-07-19 23:59:57

0

聲明

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

行不通,你想分配的東西給一個函數的返回值。我不知道你如何定義節點,但你可能意味着類似於

curr->Data = nextEl.Data(); 

即,將某物分配給節點的成員。

+0

'curr-> Set(nextEl.Data())',顯然 – 2012-07-19 22:29:06

+0

請注意,分配給如果函數返回一個引用,函數的返回值*可以*工作。這是否恰當是完全不同的問題。 – 2012-07-19 22:31:35

+0

ups,我沒有看到Node的定義就在那裏:)是的,你是對的Ben。 – timos 2012-07-19 22:31:48

0

變化

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

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