2014-09-23 96 views
0

因此,這與作業分配有關,但我不打算在此處轉儲它。我真的很想學習C++,出於某種原因,我只是在節點維護上很慢。我的問題與檢查鏈表是否爲空有關。搜索鏈接列表是否爲空

我有這樣的開始代碼:

void add_node(node*& head_ptr, const int& payload) 
{ 
node* my_first_node = new node(); 
my_first_node->data = payload; 
my_first_node->next = nullptr; 


} 

這個頭文件

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

我想知道如果我要我的附加功能之前,做一個while循環,或作爲其一部分它?我有點失落,只是想讓那部分變成現實,但我確信一旦發生這種情況我就會得到它。

謝謝!

+0

'add_node()'應該添加到鏈表的末尾嗎? – 0x499602D2 2014-09-23 02:47:35

回答

1

所以如果你只有頭指針,那麼你需要遍歷它直到結束節點。

首先你應該檢查head_ptr是否存在。

if (head_ptr == nullptr) 
    // assign your first node to the head pointer 

否則您需要到達列表的末尾。由於這是作業,那麼一些僞代碼如何?

make a node of interest, call it end_node 
while we are not at the end //How can we tell if we are at the end (hint you assign the 
          // next in your add already check for this) 

    move to the next node (interest_node = interest_node->next) 
end 

現在我們在末端節點,因此您可以在末尾添加新節點。

提示(你可能要檢查損壞的鏈接列表即循環鏈接。

+0

@達利弗蘭克沒問題。 – 2014-09-23 04:36:01

0

我認爲你需要像

head_ptr->next = my_first_node; 

內「add_node」功能

這會讓你的head_ptr添加一個「真正的」新節點。

和你的問題(add_node之前的循環)

只是做這樣的事情

while(head_ptr != nullptr){ 
... //your code (maybe you can backup the last node in here?) 

// write code for head ptr = next node 
} 

但記得備份你的「真實」 head_ptr分配「下一步」你head_ptr之前。

否則你不能拿回來