C++类实现链表结构报错:求解,或者有什么办法能提前del节点,而不是只能最后在del

错误内容:

free(): invalid pointer
Aborted (core dumped)

位置:

delet delNode时会报错;

#include<iostream>
#include<stdlib.h>
using namespace std;

class mylist
{
private:
    int index;
    mylist* next;
    static mylist* head;
public:
    mylist(bool h=0)
    {
        if(!h)
        {    
            if(head==NULL)
            {
                head=this;
                head->next=NULL;
                head->index=0;
            }
            else
            {
                this->next=head->next;
                head->next=this;
                this->index=head->index;
                head->index++;
            }
        }
        else
        {
            //尾插法
        }
    }
    static int deleteNode(int index);
    static void printLsit();
};

mylist* mylist::head=NULL;

int mylist::deleteNode(int index)
{
    mylist* curNode;
    mylist* delNode;
    curNode=head;
    delNode=curNode->next;
    while(delNode!=NULL)
    {
        if(delNode->index==index)
        {
            curNode->next=delNode->next;
            delNode->next=NULL;
            delete delNode; //为什么不能del ,报错free(): invalid pointer Aborted (core dumped)
            delNode=NULL; 
            return 0;       
        }
        else 
        {
            curNode=delNode;
            delNode=delNode->next;
        }
    }
    return -1;
}

void mylist::printLsit()
{
    mylist* curNode;
    curNode=head;
    while(curNode!=NULL)
    { 
        cout<<curNode->index<<"->";
        curNode=curNode->next;
    }
    cout<<"NULL"<<endl;
}

int main()
{
    /* 头在全局区,其它节点在堆区 */
    mylist *plst=new mylist[10];
    if(plst->deleteNode(1)==-1) cout<<"del failed"<<endl;
    else cout<<"del successed"<<endl;
    delete []plst;
    /* 头在全局区,其它节点在栈区 */
    /* mylist lst[10];
    lst->printLsit();
    if(lst->deleteNode(1)==-1) cout<<"del failed"<<endl;
    else cout<<"del successed"<<endl;
    lst->printLsit(); */
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值