双向链表可以跟单向链表比较优点在可以在两边进行添加删除元素
Doulist类声明及定义:
#include <string>
struct DouListNode {
int elem;
DouListNode *prev, *next;
DouListNode(int e = 0, DouListNode *p = 0, DouListNode *n = 0) {
elem = e;
prev = p;
next = n;
}
};
class DouList {
private:
DouListNode *m_head, *m_tail;
public:
DouList();
DouList(const DouList &src);
~DouList();
void clear();
bool empty() const;
std::string to_str() const;
int front() const;
int back() const;
void push_front(const int &e);
void push_back(const int &e);
void pop_front();
void pop_back();
void operator=(const DouList &other);
friend std::ostream& operator<<(std::ostream &out,
const DouList &list);
// non-meaning static value
static int _error_sign; // for illegal front()/back()
};
int DouList::_error_sign = -1;
DouList::DouList() {
m_head = m_tail = 0;
}
DouList::DouList(const DouList &src) {
m_head = m_tail = 0;
*this = src;
}
DouList::~DouList() {
this->clear();
}
void DouList::clear() {
DouListNode *t;
while (m_head) {
t = m_head;
m_head = m_head->next;
delete t;
}
m_head = m_tail = 0;
}
bool DouList::empty() const {
return m_head == 0 ? true : false;
}
std::string DouList::to_str() const {
long long int tmp;
std::string ret = "[";
if (!this->empty()) {
DouListNode *p = m_head->next;
tmp = m_head->elem;
ret += std::to_string(tmp);
while (p) {
tmp = p->elem;
ret += ", " + std::to_string(tmp);
p = p->next;
}
}
ret += "]";
return ret;
}
int DouList::front() const {
if (!this->empty())
return m_head->elem;
else
return _error_sign;
}
int DouList::back() const {
if (!this->empty())
return m_tail->elem;
else
return _error_sign;
}
void DouList::push_front(const int &e) {
if (this->empty()) {
m_head = m_tail = new DouListNode(e);
} else {
m_head->prev = new DouListNode(e, 0, m_head);
m_head = m_head->prev;
}
}
void DouList::push_back(const int &e) {
if (this->empty()) {
m_head = m_tail = new DouListNode(e);
} else {
m_tail->next = new DouListNode(e, m_tail);
m_tail = m_tail->next;
}
}
void DouList::pop_front() {
if (this->empty())
return;
if (m_head == m_tail) {
this->clear();
return;
} else {
m_head = m_head->next;
delete m_head->prev;
m_head->prev = 0;
}
}
void DouList::pop_back() {
if (this->empty())
return;
if (m_head == m_tail) {
this->clear();
} else {
m_tail = m_tail->prev;
delete m_tail->next;
m_tail->next = 0;
}
}
void DouList::operator=(const DouList &other) {
this->clear();
m_head = m_tail = 0;
if (other.empty())
return;
m_head = new DouListNode(other.m_head->elem);
DouListNode *p = m_head;
DouListNode *q = other.m_head->next;
while (q) {
p->next = new DouListNode(q->elem, p);
p = p->next;
q = q->next;
}
m_tail = p;
}
std::ostream& operator<<(std::ostream &out, const DouList &list) {
out << list.to_str();
return out;
}