2012-11-11 100 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

这只是一个无限循环,只要你继续输入,就添加元素;) –