好吧,我知道這是一個可笑的簡單問題,但由於某種原因,我無法獲得鏈接列表的工作。這可能只是因爲我真的很累,因爲我以前做過一百萬次。把我的程序放到最簡單的可能實現中,仍然無法工作。鏈接列表類
非常基本的實現,只是做一個整數的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;
}
}
你的main中的while循環將不起作用,因爲'i'的值永遠不會改變。 'while(i == 0)'永遠不會是錯誤的。 – 0x499602D2
什麼不起作用?描述你正在得到的不需要的行爲 – amit
當然,在實際的代碼中,你應該使用'std :: list'(或者如果你有一個C++ 11編譯器'std :: forward_list ')。 –