jazm_blk 2017-12-05 12:35 采纳率: 100%
浏览 1099
已采纳

关于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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥40 求一款能支持ios15以上的屏蔽越狱插件。比较好用的
  • ¥15 C++ QT对比内存字符(形式不定)
  • ¥30 C++第三方库libiconv 远程安装协助
  • ¥15 https://github.com/youlaitech/vue3-element-admin/blob/master/src/store/modules/user.ts 这2句代码如何理解
  • ¥15 duilib开发文本字串超过长度显示
  • ¥20 mysql的.ibd文件为啥那么多
  • ¥15 C++中采用栈和BFS算法求解迷宫问题
  • ¥15 关于#java#的问题:这是跳转失败出现的界面这是哪个出现问题的servlet(开发工具-ide)
  • ¥15 EBS R12费用采购跨月冲销
  • ¥15 python中用mplfinance如何做到多股同列?