2012-11-11 101 views
0

好吧,我知道這是一個可笑的簡單問題,但由於某種原因,我無法獲得鏈接列表的工作。這可能只是因爲我真的很累,因爲我以前做過一百萬次。把我的程序放到最簡單的可能實現中,仍然無法工作。鏈接列表類

非常基本的實現,只是做一個整數的LL,我做了一百萬次之前,但無論出於什麼原因,它永遠不會前進的頭。

的main.cpp

#include <iostream> 
#include "ll.h" 
using namespace std; 

int main() 
{ 
    int x; 
    list ll; 
    int i =0; 


    while(i == 0) 
    { 
    cout << "Enter a value to add to the LL "; 
    cin >> x; 

    ll.add(x); 
    ll.display(); 
    } 

return 0; 
} 

ll.h

struct node 
{ 
    int val; 
    node * next; 
}; 

class list 
{ 
    public: 
    list(); 

    void add(int); 
    void display(); 
    node * head; 
}; 

ll.cpp

#include <iostream> 
#include "ll.h" 
using namespace std; 

list::list() 
{ 
    head = NULL; 
} 

void list::add(int x) 
{ 
    if(!head) 
    { 
     cout << "First " << endl; 
     head = new node; 
     head->val = x; 
     head->next = NULL; 
    } 
    else 
    { 
     node * current = head; 
     while (current) 
      current = current->next; 

     current = new node; 
     current->val = x; 
     current->next = NULL; 

    } 
} 

void list::display() 
{ 
    node * current = head; 

    while(current) 
    { 
     cout << current->val << endl; 
     current = current->next; 
    } 
} 
+1

你的main中的while循環將不起作用,因爲'i'的值永遠不會改變。 'while(i == 0)'永遠不會是錯誤的。 – 0x499602D2

+1

什麼不起作用?描述你正在得到的不需要的行爲 – amit

+0

當然,在實際的代碼中,你應該使用'std :: list '(或者如果你有一個C++ 11編譯器'std :: forward_list ')。 –

回答

2

看來要附加到 列表。在這種情況下,循環條件不應該是

while (current) 

while (current->next) 

確保最初是不NULL(你與你的支票爲'頭做的)。

實際上,設置新節點的邏輯也不太正確。你可能想擁有第二分支的add()是這個樣子:

while (current->next) { 
    current = current->next; 
} 
current->next = new node(x); 

...用node合適的構造函數:

node::node(int x): val(x), next() {} 
+1

做完'current-> next = new Node',而不是立即用新值覆蓋'current' – amit

+0

@amit:yes - 附加代碼有多種錯誤... –

+0

我同意,只是對最終答案的補充。我完全同意並提出了答案。 – amit

1

除了迪特馬爾的答案,你有一個不正確的,而循環:

while (i == 0) { 
    ... 
} 

在for循環的身體,i是從來沒有改變過,它導致無限循環。雖然我不完全確定你想使用i

+0

這只是一個無限循環,只要你繼續輸入,就添加元素;) –