Immortal463 2022-11-27 00:43 采纳率: 37.5%
浏览 9
已结题

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

#include <iostream>
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!"<<endl;
    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!"<<endl;
        }    
    }
    return head;
}
void print(struct staff*head)
{
    struct staff *p=head;
    while(p!=NULL)
    {
        cout<<p->num<<' '<<p->name<<' '<<p->wage<<' ';
        p = p->next;   
    }
    cout<<endl;
}    
int main()
{
    int x;
    cout<<"Please input the acount of the staff:"<<endl;
    cin>>x;
    struct staff*head=NULL;
    struct staff*newstaff,*tail;
    for(int i=0;i<x;i++)
    {
        newstaff=new 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:"<<endl;
    int n;
    cin>>n;
    struct staff*y=del(head,n);
    print(y);
    system("pause");
    return 0;
}

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

  • 写回答

6条回答 默认 最新

  • X-道至简 2022-11-27 08:11
    关注
    获得7.50元问题酬金

    这里应该是当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;
            }
    
    评论

报告相同问题?

问题事件

  • 系统已结题 12月5日
  • 赞助了问题酬金15元 11月27日
  • 创建了问题 11月27日

悬赏问题

  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档
  • ¥50 C++五子棋AI程序编写
  • ¥30 求安卓设备利用一个typeC接口,同时实现向pc一边投屏一边上传数据的解决方案。