Algorithm_fromBilibili
Algorithm_fromBilibili copied to clipboard
你的双向链表的头插法有误
你没有考虑链表为空的情况,如果L->next为NULL,则无法执行p->next = L->next。 正确的应该这样
void CreatListHead(LinkList &L, const int n)
{
for (int i = 0; i < n; ++i)
{
DuLnode *p = new DuLnode;
if (p == NULL)
{
cout << "Memory allocation failed." << endl;
return;
}
p->note.name = rand_str(5);
// cin >> "input name:">>p->note.name;
p->note.age = rand() % 100;
// cin >> "input age:">>p->note.age;
p->prior = L;
if (L->next == NULL)
{ // the list is empty
p->next = NULL;
}
else
{ // the list is not empty
p->next = L->next;
L->next->prior = p;
}
L->next = p;
}
}