我是新來的,所以我幾乎沒有學習如何實現鏈表。我輸入一個數字時程序崩潰了。我想將節點添加到名單的後面。C++添加到雙向鏈表的末尾
這是節點
struct node
{
int data;
node *next;
node *prev;
};
這是附加功能
void Add(node* &head, int newdata)
{
//create a new node to hold the data with a terminal (NULL) next pointer
node *tmp = new node;
tmp->data = newdata;
tmp->next;
node *current = head;
//check whether head has been initialized (is NULL)
// if not, make the new node head and set prev
if (head != NULL)
{
tmp = head;
tmp->prev = NULL;
}
//if head has been initialized
//find the end of the chain with a pointer
else
{
while (current->next != NULL)
{
current = current->next;
}
}
//add the new node on to the last node in the list
//set pointers both forward and backwards
tmp = current;
tmp->prev = current->prev->next;
tmp->next = current->next;
}
如果(head)爲NULL,那麼(current)也會被初始化爲NULL,然後while(current-> next!= NULL)循環條件將取消引用NULL指針,並且會在那裏崩潰。 – 2014-10-03 01:32:58