您好,欢迎来到尚车旅游网。
搜索
您的当前位置:首页C++模板--List容器

C++模板--List容器

来源:尚车旅游网
C++模板--List容器

//构造//析构

//拷贝构造//赋值构造//=//<templateclass List{ class Node{ public:

Node(const T& data, Node* prev = NULL, Node* next = NULL):m_data(data),m_prev(prev),m_next(next){} friend ostream& operator<<(ostream& os, const Node& node){ return os << \"[\"<< node.m_data << \"]\"; }

T m_data;

Node* m_prev; Node* m_next; };

Node* m_head; Node* m_tail;

public:

List():m_head(NULL), m_tail(NULL){} ~List(){ clear(); }

List(const List& that):m_head(NULL), m_tail(NULL){

for(Node* node = that.m_head; node; node = node->m_next){ this->push_back(node->m_data); } }

List& operator=(const List& that){ if(this != &that){ List temp = that;

swap(m_head, temp.m_head); swap(m_tail, temp.m_tail); }

return *this; }

void clear(void){

for(Node* node = m_head, *next; node; node = next){ next = node->m_next; delete node; }

m_head = NULL; m_tail = NULL; }

bool empty(void) const {

return !m_head && !m_tail; }

size_t size(void)const{ size_t count = 0;

for(Node* node = m_head; node; node = node->m_next){ count++;

}

return count; }

T& front(void){ if(empty()){

throw underflow_error(\"list under flow\"); }

return m_head->m_data; }

const T& front(void) const{

return const_cast(this)->front(); }

void push_front(const T& data){

m_head = new Node(data, NULL, m_head); if(m_head->m_next){

m_head->m_next->m_prev = m_head; }else{

m_tail = m_head; } }

void pop_front(void){ if(empty()){

throw underflow_error(\"list under flow\"); }

Node* temp = m_head; m_head = m_head->m_next; delete temp; temp = NULL; if(m_head){

m_head->m_prev = NULL; }else{

m_tail = NULL; } }

T& back(void){ if(empty()){

throw underflow_error(\"list under flow\"); }

return m_tail->m_data; }

const T& back(void) const {

return const_cast(this)->back(); }

void push_back(const T& data){

m_tail = new Node(data, m_tail, NULL); if(m_tail->m_prev){

m_tail->m_prev->m_next = m_tail; }else{

m_head = m_tail; } }

void pop_back(void){ if(empty()){

throw underflow_error(\"list under flow\"); }

Node* temp = m_tail; m_tail = m_tail->m_prev; delete temp; temp = NULL; if(m_tail){

m_tail->m_next = NULL; }else{

m_head = NULL; }

}

void remove(const T& data){

for(Node* node = m_head, *next; node; node = next){ next = node->m_next; if(data == node->m_data){ if(node->m_prev){

node->m_prev->m_next = node->m_next; }else{

m_head = node->m_next; }

if(node->m_next){

node->m_next->m_prev = node->m_prev; }else{

m_tail = node->m_prev; }

delete node; } } }

friend ostream& operator<<(ostream& os, const List& list) {

for(Node* node = list.m_head; node; node = node->m_next) {

os << *node; }

return os; }};

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- sceh.cn 版权所有 湘ICP备2023017654号-4

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务