2014-09-23 65 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之前。

否则你不能拿回来