jazm_blk 2017-12-05 12:35 采纳率: 100%

# 关于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;
}

``````

• 写回答

#### 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;
}
``````
本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 悬赏问题

• ¥40 求一款能支持ios15以上的屏蔽越狱插件。比较好用的
• ¥15 C++ QT对比内存字符（形式不定）
• ¥30 C++第三方库libiconv 远程安装协助