我是新手,因此我几乎没有学习如何实现链接列表。当我输入数字时,我的程序崩溃。我想将节点添加到列表的后面。
这是节点
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;
}
答案 0 :(得分:0)
开始时,您需要将tmp->next
和tmp->prev
设置为NULL。
垃圾指针每次都会杀了你。
然后你似乎认为head == NULL
意味着它已被初始化,而它可能意味着相反。
最后,您设置了tmp = current;
,因此您将丢弃要添加的节点。
尝试再次完成最后三行。
另外,请使用调试器进行操作,以防您无法查看自己正在做的事情。
答案 1 :(得分:0)
嗯,你在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;
}
答案 2 :(得分:0)
这条线应该做什么?
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
将是什么。
答案 3 :(得分:0)
你需要做更多这样的事情:
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...