2011-06-06 90 views
3

我想實現一個簡單的鏈接列表。初始值插入成功,但未正確輸入下一個元素。請幫我解決錯誤是什麼。謝謝感謝。麻煩實現鏈表

#include<iostream> 

using std::cout; 

class node 
{ 
    public: 
     node():next(0){} 
     void setNext(node *next){ next = next; } 
     node* getNext(){ return next; } 
     void setValue(int val){ value = val; } 
     int getValue(){ return value; } 

    private: 
     int value; 
     node *next; 
}; 

class list 
{ 
    public: 
     list():head(new node()),len(0){} 
     bool insert(int value); 
     //bool remove(int value); 
     int valueAt(int index); 
     int length(); 

    private: 
     node *head; 
     int len; 

}; 

bool list::insert(int value) 
{ 
    node *current = 0; 
    node *previous = 0; 
    node *temp = 0; 

    temp = new node(); 
    temp->setValue(value); 

    current = head; 
    previous = head; 

    while((temp->getValue())>(current->getValue())) 
    { 
     previous = current; 
     current = current->getNext(); 

     if(!current) 
     { 
      break; 
     } 
    } 

    if(current == head) 
    { 
     temp->setNext(current); 
     head = temp; 

     len++; 
    } 
    else 
    { 
     temp->setNext(current); 
     previous->setNext(temp); 

     len++; 
    } 
} 

int list::valueAt(int index) 
{ 
    if((index < len) && (index >= 0)) 
    { 
     node *current = 0; 
     current = head; 
     int count = 0; 

     while(count < index) 
     { 
      current = current->getNext(); 
      count++; 
     } 

     return (current->getValue()); 
    } 
    else 
    { 
     return -1; 
    } 
} 


int main() 
{ 
    list myList; 

    myList.insert(5); 
    myList.insert(20); 
    myList.insert(10); 

    cout<<"Value at index 1 : "<<myList.valueAt(1); 

    return 0; 
} 
+0

這是功課?它確實看起來像它。如果是這種情況,你應該已經標記了你的問題。 – 2011-06-06 17:17:55

+2

@大衛不要這麼快就譴責這功課,有些人就是喜歡練,和鏈表是特別有趣。 – 2011-06-06 17:19:05

+0

接受的答案,如果您的問題固定 – 2011-06-06 17:34:03

回答

3

粗略地看一眼後,也許問題是

void setNext(node *next){ next = next; } 

您指定給本身就是一個變量,因爲局部變量掩蓋實例變量。嘗試改變,要

void setNext(node *next){ this->next = next; } 

在其他注意事項:

  1. list::list,你或許不應該初始化headnew node。這將意味着你的鏈表將對創建一個任意節點,但有長度爲0的你應該考慮設置headNULL代替。

  2. 創建時,node s有隨機value。考慮在構造函數中需要一個參數,或者一個適當的默認值。

  3. -1是一個壞的「無效值」爲list::valueAt,因爲它也是存儲節點的有效價值。

  4. 您應該將list類重命名爲slist以指示它按排序順序存儲值。

+0

噢,我的上帝......我想我是很愚蠢的...感謝您指出了這一點。非常感謝。 – Ramila 2011-06-06 17:22:11

+0

@Ramilla你不傻,我以前也做過。或者它可能是我們都很愚蠢。 – 2011-06-06 17:23:22