关于链表的问题(为什么要在del函数结束后再创一个变量y)

#include 
using namespace std;
struct staff
{
    char num[6];
    char name[20];
    double wage;
    struct staff*next;
};
staff*del(struct staff*head,int n)
{
    int i=1;
    struct staff*p,*q;
    p=head;
    if(head==NULL)
        cout<<"The list is null!"<else
    {
        if(n==1)
        {
            head=p->next;
            delete p;
        }
        else
        {
            while(i!=n&&p!=NULL)
            {
                i++;
                q=p;
                p=p->next;
            }
            if(n==i&&p!=NULL)
            {
                q->next=p->next;
                delete p;
            }
            else
                cout<<"can't find it!"<return head;
}
void print(struct staff*head)
{
    struct staff *p=head;
    while(p!=NULL)
    {
        cout<num<<' '<name<<' '<wage<<' ';
        p = p->next;   
    }
    cout<int main()
{
    int x;
    cout<<"Please input the acount of the staff:"<>x;
    struct staff*head=NULL;
    struct staff*newstaff,*tail;
    for(int i=0;inew staff;//指针指向的地址需要储存数据需要申请空间
        cin>>newstaff->num>>newstaff->name>>newstaff->wage;
        if(head==NULL)
            head=newstaff;
        else
            tail->next=newstaff;
        tail=newstaff;
    }
    tail->next=NULL;
    print(head);
    cout<<"Please input the number of the staff you want to delete:"<int n;
    cin>>n;
    struct staff*y=del(head,n);
    print(y);
    system("pause");
    return 0;
}

为何在最后要新建一个变量y,直接使用head进行print就会报错

这里应该是当n=1的时候会有问题,head开始指向的已经被释放了,在用head访问会出现空指针问题
如下面代码注释

staff*del(struct staff*head,int n)
{
    int i=1;
    struct staff*p,*q;
    /*head赋值给p*/
    p=head;
    if(head==NULL)
        cout<<"The list is null!"<else
    {
        if(n==1)
        {
            /*head的值改变,为返回值做准备*/
            head=p->next;
            /*p目前为head,然后被释放掉了,如果后面再用head访问,将会出现空指针的错误*/
            delete p;
        }

因为你这个链表没有固定头节点,所以被删除的可能是第一个节点,那么导致head会发生变化。而del函数只是传递head指针作为参数,因此是不能通过参数实现head自身地址修改的,只能通过return方式将新的head指针返回给外部调用代码。所以定义一个新的y指针接收del函数返回的新的head指针,才能实现删除元素后的新链表数据的输出

单链表是一种链式存取的数据结构,其表中的数据是以结点来表示的,每个结点构成有:元素(本结点数据)+指针(后继元素储存位置)

参考一下

参考