[英]c++ adding to the end of a doubly linked list
我对此并不陌生,所以我几乎不学习如何实现链表。输入数字时我的程序崩溃。我想将节点添加到链表的后面。
这是节点
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;
}
首先,您需要将tmp->next
和tmp->prev
为NULL。 每次垃圾指针都会杀死您。
然后,您似乎认为head == NULL
表示已初始化,而可能相反。
最后,设置tmp = current;
,因此您将丢弃要添加的节点。
尝试再次遍历最后三行。
另外,如果您看不到正在做什么,请与调试器一起使用。
好吧,在该add
函数中发生了一些奇怪的事情,这可能有助于您理解该过程:
void add(node* &head, int dataToAdd){
node* newNode = new node();
newNode->data = dataToAdd;
if(!head){ // checking to see if head was passed in or is null
head = newNode;
return;
}
node* current = head;
node* next = current->next;
// iterate through the list till next == Null( hits 1 after the end)
while(current->next){
current = next;
next = next->next;
}
//Set the end of the list to the newly added node
next = newNode;
next->prev = current;
}
这条线应该做什么?
tmp->next;
不时使用链表可能是真正的大脑锻炼。 我建议您直接将指针初始化为NULL。 关于最后三行,需要再次考虑。
tmp = current; //This discards your newly created node, which results in a memory leak
tmp->prev = current->prev->next; // The previous node is simply 'current'
tmp->next = current->next; // You know that the next node will be NULL
current
节点还需要知道新的current->next
将是什么。
您需要做的更像是这样:
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 = NULL;
tmp->prev = NULL;
if (!head)
head = tmp;
else
{
//find the end of the chain with a pointer
node *last = head;
while (last->next != NULL )
last = last->next;
//add the new node on to the last node in the list
//set pointers both forward and backwards
last->next = tmp;
tmp->prev = last;
}
}
如果跟踪头节点和最后一个节点,则插入将更快,因为您不必每次都遍历整个列表,例如:
struct list
{
node *head;
node *tail;
};
void Add(list &l, int newdata)
{
node *tmp = new node;
tmp->data = newdata;
tmp->next = NULL;
if (!l.head)
l.head = tmp;
tmp->prev = l.tail;
if (tmp->prev)
tmp->prev->next = tmp;
l.tail = tmp;
}
话虽如此,由于您使用的是C ++,因此您实际上应该使用std::list
,它可以为您处理所有这些事情:
#include <list>
std::list<int> mylist;
mylist.push_back(12345);
// etc...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.