Algorithm_fromBilibili icon indicating copy to clipboard operation
Algorithm_fromBilibili copied to clipboard

你的双向链表的头插法有误

Open spy1130 opened this issue 1 year ago • 0 comments

你没有考虑链表为空的情况,如果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;
    }
}

spy1130 avatar Apr 11 '23 09:04 spy1130