64,282
社区成员
发帖
与我相关
我的任务
分享
template<typename T>
class List{
private:
class Node{
public:
T m_data;
Node* m_prev;
Node* m_next;
Node(const T& data,Node* prev = NULL,Node* next = NULL):m_data(data),m_prev(prev),m_next(next){}
friend ostream& operator<<(ostream& os,Node node){
return os<< '[' << node.m_data << ']';
}
};
Node* m_head;
Node* m_tail;
public:
List(void):m_head(NULL), m_tail(NULL){}
~List(void){
clear();
}
List(const List& that):m_head(NULL), m_tail(NULL){
for(Node* node = that.m_head;node;node=node->m_next)
push_back(node->m_data);
}
List& operator=(const List& that){
if(&that != this){
List list(that);
swap(m_head,list.m_head);
swap(m_tail,list.m_tail);
}
return *this
}
T& front(void){
return m_head->m_data;
}
const T& front(void)const{
return const_cast<List*>(this)->front();
}
List& 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;
}
return *this;
}
List& pop_front(void){
Node* node=m_head->m_next;
delete m_head;
m_head=node;
if(m_head){
m_head->m_next->m_prev=NULL;
}else{
m_tail=NULL;
}
return *this;
}
T& back(void){
return m_tail->m_data;
}
const T& back(void)const{
return const_cast<List*>(this)->back();
}
List& 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;
}
return *this;
}
List& pop_back(void){
Node* node=m_tail->m_prev;
delete m_tail;
m_tail=node;
if(m_tail){
m_tail->m_prev->m_next = m_tail;
}else{
m_head=NULL;
}
return *this;
}
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;
node->m_next->m_prev=node->m_prev;
}else{
m_head=node->m_next;
}
if(node->m_next){
node->m_next->m_prev=node->m_prev;
node->m_prev->m_next=node->m_next;
}else{
m_tail=node->m_prev;
}
delete node;
}
}
}
void clear(void){
for(Node* next; m_head;m_head=next){
next=m_head->m_next;
delete m_head;
}
m_tail=NULL;
}
bool empty(void)const{
return m_head == m_tail;
}
size_t size(void)const{
int counter=0;
for(Node* node=m_head;node;node=node->next){
counter++;
}
return counter;
}
friend ostream& operator<<(const List& list){
os << *(list.m_head);
return os;
}
};