jazm_blk
2017-12-05 12:35
采纳率: 100%
浏览 1.0k

关于c++中的双向循环链表

 #pragma once
#define V_TPLS template<class T>\
                void MyList<T>::

template<class T>
class MyList
{
    T data;
    MyList* next, *back;
public:
    MyList()
    {
        next = this;
        back = this;
        data = 0;
    }
    //在链表后插入数据
    void push_back(T data);
    //在链表前插入数据
    void push_front(T data);//前继
    //清空整个链表
    void _clear()
    {
        while (this->next!=this)
        {
            MyList *temp = this->next;
            this->next = this->next->next;
            delete temp;
        }
    }

    void put()
    {
        MyList *p = this->next;
        while (p!=this)
        {
            cout << p->data << ends;
            p = p->next;
        }
    }

    ~MyList()
    { _clear(); }
};

//在链表后插入数据
V_TPLS push_back(T data)
{
    MyList *temp = new MyList;
    temp->data = data;
    static MyList*p_n = this;
    temp->next = p_n->next;
    temp->back = p_n;
    p_n->next = temp;
    p_n = p_n->next;
    this->back = temp;
}
//在链表前插入数据
V_TPLS push_front(T data)
{
    MyList *temp = new MyList;
    temp->data = data;
    temp->next = this->next;
    temp->back = this;
    this->next->back = temp;
    this->next = temp;
}


为什么我的_clear()运行的时候this指针的地址为什么会改变呢?
每次运行到_clear()函数时就会报错

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • God_Gray 2017-12-05 15:00
    已采纳

    _clear() push_back() push_front()函数都有问题,改了三个函数的代码,你参照看下。

        void _clear()
        {
            while (this->next != this)
            {
                MyList *temp = this->next;
                this->next = temp->next;
                temp->next->back = temp->back;
    
                temp->next = temp;
                temp->back = temp;
                delete temp;
            }
        }
    
    //在链表后插入数据
    V_TPLS push_back(T data)
    {
        MyList* newList = new MyList;
        newList->data = data;
    
        MyList* temp = this->next;
        this->next = newList;
        newList->next = temp;
        newList->back = this;
        temp->back = newList;
    }
    
    //在链表前插入数据
    V_TPLS push_front(T data)
    {
        MyList* newList = new MyList;
        newList->data = data;
    
        MyList* temp = this->back;
        this->back = newList;
        newList->back = temp;
        newList->next = this;
        temp->next = newList;
    }
    
    点赞 评论
  • MikarLittle 2017-12-06 10:46

    _clear() push_back() push_front()函数都有问题

    点赞 评论
  • jazm_blk 2017-12-07 13:26

    你的程序我试了试,还是不行,无法析构.但是我找到原因了,并不是我的函数体结构写的有问题,
    此问题程序的关键是不能使用delete重载的运算符,而要使用free,这样就一点问题也没有了

    不知道为什么delete总是会改变我的this指针,导致无法析构

     //清空整个链表
    V_TPLS _clear()
    {
        while (this->next != this)
        {
            MyList *temp = this->next;
            this->next = this->next->next;
            free(temp);
        }
        size = 0;
    }
    
    

    我还真不太了解delete与free的区别,但是这点区别就是我程序的bug所在之处

    点赞 评论

相关推荐 更多相似问题