单链表简单实现

用作复习,简单实现下单链表,这里我自己添加了个尾指针。

#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;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值