我有這個代碼的問題。我對C++相當陌生,但其中大部分已經很容易理解。我試圖做一個簡單的鏈接列表數據結構,但是,它打印垃圾而不是列表中的值。我的問題是,我的語法錯在哪裏顯示地址?C++節點和鏈接列表語法
輸出:
class Node
{
public:
int data;
Node *next;
Node(int data)
{
data = data;
next = NULL;
};
};
class LinkedList
{
Node *first;
Node *last;
int count;
public:
LinkedList()//constructor for the LinkedList
{
//initialization
first = NULL;
last = NULL;
count = 0;
};
void AddItem(int data)
{
Node *newItem = new Node(data);
if(first == NULL)
{
first = newItem;
last = newItem;
}
else
{
Node *traversal = first;
while(traversal->next != NULL)
{
traversal = traversal->next;
}
traversal->next = newItem;
last = traversal->next;
}
count++;
}
void DisplayList()
{
cout<<endl;
Node *traversal = first;
while(traversal->next != NULL)
{
cout<<"["<<traversal->data<<"] ";
traversal = traversal->next;
if(traversal == NULL)
{
break;
}
}
}
bool isEmpty()
{
if(count < 1)
{
cout<<"List is empty";
return true;
}
else
{
cout<<"List is not empty";
return false;
}
}
};
int main()
{
cout <<"Linked Lists demo"<<endl;
LinkedList collection;
collection.AddItem(1);
collection.AddItem(3);
collection.AddItem(5);
collection.AddItem(7);
collection.AddItem(9);
collection.AddItem(11);
collection.isEmpty();
collection.DisplayList();
cin.get();
請嘗試在運行時嘗試調試並放置斷點以檢查各種分配。 – abnvp
您的成員變量名稱看起來像普通變量名稱,因此您陷入了一個非常常見的陷阱。一個常見的慣例是用m_例如m_data爲成員變量加上前綴。嘗試使用你的代碼,然後檢查Node的構造函數 – kfsone