- list基本链表容器的实现:
代码:
#include<iostream>
using namespace std;
template<typename T>
class list
{
private:
class node//节点
{
public:
node(const T &data, node * p, node* n): m_data(data),m_pre(p), m_next(n){}//构造函数
T m_data;
node* m_pre;//前驱
node* m_next;//后继
};
node* m_head;//链表头节点
node* m_tail;//链表未节点
public:
//缺省构造
list():m_head(nullptr), m_tail(nullptr){}
//复制构造
list(const list& that) {
for (node* p = that.m_head; p; p = p->m_next)
push_back(p->m_data);
}
//析构函数
~list() {
clear();
}
//判断链表是否为空
bool empty() {
return m_head == nullptr && m_tail == nullptr;
//头节点等于尾节点并且为空就说明链表为空
}
//链表清空
void clear() {
while (!empty())
pop_prent();//循环调用输出头结点或者输出未结点的函数都可以
}
//添加头节点
void push_prent(const T & data) {
m_head = new node(data, nullptr, m_head);
if (m_head->m_next)
m_head->m_next->m_pre = m_head;
else
m_tail = m_head;
}
//删除头节点
void pop_prent() {
if (empty())
return;
node* ponde = m_head->m_next;
delete m_head;
if (ponde)
ponde->m_pre = nullptr;
else
m_tail = nullptr;
m_head = ponde;
}
//添加未节点
void push_back(const T& data) {
m_tail = new node(data, m_tail, nullptr);
if (m_tail->m_pre)
m_tail->m_pre->m_next = m_tail;
else
m_tail = m_head;
}
//删除尾节点
void pop_back() {
if (empty())
return;
node* ponde = m_tail->m_pre;
delete m_tail;
if (ponde)
ponde->m_next = nullptr;
else
m_head = nullptr;
m_tail = ponde;
}
//获取链表头元素
T& get_prent() {
if (empty())
throw underflow_error("链表为空。");//抛出异常
return m_head->m_data;
}
const T& get_prent() const {
return const_cast<list*>(this)->get_prent();//去除const属性,调用上面的函数。
}
//获取链表未元素
T& get_back() {
if(empty())
throw underflow_error("链表为空。");//抛出异常
return m_tail->m_data;
}
const T& get_back()const {
return const_cast<list*>(this)->get_back();
}
//获取链表大小
size_t get_size() {
size_t i = 0;
for (node* p = m_head; p; p = p->m_next)
++i;
return i;
}
//重载输出<<运算符
friend ostream& operator<<(ostream& os, list& ls);
};
ostream& operator<<(ostream& os, list<int>& ls)
{
for (list<int>::node* p = ls.m_head; p; p = p->m_next)
os << p->m_data << " ";
return os;
}
//代码模拟容器部分
//============================================================
//代码模拟用户部分
int main()
{
list<int> ls;
for (int i = 0; i < 5; i++)
ls.push_prent(10 + i);
for (int i = 0; i < 5; i++)
ls.push_back(100 + i);
cout << ls << endl;
ls.pop_back();
ls.pop_prent();
cout << ls << endl;
return 0;
}