用作复习,简单实现下单链表,这里我自己添加了个尾指针。
#include<iostream>
using namespace std;
template<class T>
struct Node{
T _val;
Node<T>* _next;
Node(const T& val)
:_val(val)
,_next(NULL)
{}
};
template<class T>
class List{
typedef Node<T> Node;
public:
List<T>();
~List();
List(const List& l);
List& operator=(const List& l);
void push_back(const T& val);
void pop_back();
pair<Node*,bool> find(const T& val);
bool Delete(const T& val);
public:
Node* BuyNode(const T& val);
void erase();
private:
Node* head;
Node* tail;
};
template<class T>
List<T>::List()
: head(new Node(0))
, tail(head)
{}
template<class T>
List<T>::~List(){
}
template<class T>
List<T>::List(const List<T>& l):head(new Node(0)){
Node* cur = l.head->_next;
Node* tmp = head;
while (cur){
tmp->_next = BuyNode(cur->_val);
tmp = tmp->_next;
cur = cur->_next;
}
}
template<class T>
List<T>& List<T>::operator=(const List<T>& l){
if (this != &l){
erase();
head = new Node(0);
tail = head;
Node* cur = l.head->_next;
Node* tmp = head;
while (cur){
tail->_next = BuyNode(cur->_val);
tail = tail->_next;
cur = cur->_next;
}
}
return *this;
}
template<class T>
void List<T>::push_back(const T& val){
tail->_next = BuyNode(val);
tail = tail->_next;
}
template<class T>
void List<T>::pop_back(){
Node* cur = head;
if (head==tail)
return;
while (cur->_next != tail){
cur = cur->_next;
}
delete tail;
tail = cur;
tail->_next = NULL;
}
template<class T>
pair<Node<T>*,bool> List<T>::find(const T& val){
Node* cur = head;
while (cur->_next && cur->_next->_val!=val){
cur = cur->_next;
}
if (cur->_next)
return make_pair(cur, true);
return make_pair(cur, false);
}
template<class T>
bool List<T>::Delete(const T& val){
Node* tmp = find(val).first;
if (tmp->_next == NULL)
return false;
Node* del = tmp->_next;
if (del == tail)
tail = tmp;
tmp->_next = del->_next;
delete del;
return true;
}
template<class T>
Node<T>* List<T>::BuyNode(const T& val){
return new Node(val);
}
template<class T>
void List<T>::erase(){
while (head)
{
Node* del = head;
head = head->_next;
delete del;
}
}