Skip to content

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

@spy1130

Description

@spy1130

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions