单链表简单实现
来源:互联网 发布:cn域名注册10元 编辑:程序博客网 时间:2024/06/16 04:57
用作复习,简单实现下单链表,这里我自己添加了个尾指针。
#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
- 简单单链表C++实现
- 单链表的简单实现
- 单链表的简单实现
- 单链表的简单实现
- 单链表数据结构简单实现
- 简单单链表实现
- 单链表的简单实现
- 单链表的简单实现
- lua单链表简单实现
- 简单实现单链表
- 单链表实现(超简单)
- 数据结构 单链表简单实现
- 单链表的简单实现
- 单链表简单实现
- 单链表的简单实现
- 单链表的简单实现
- 单链表的简单实现
- 单链表简单实现
- CSS中margin介绍
- 微服务实战:百万千万级数据的实时处理架构(一)
- 文章标题
- 算法的时间复杂度与空间复杂度的理解
- python 购物车菜单
- 单链表简单实现
- 二叉搜索树与双向链表
- 四种生成和解析XML文档的方法
- 关于php和html的混编写法
- ubuntu 常见错误--Could not get lock /var/lib/dpkg/lock
- localStorage sessionStorage区别 客户端存储数据
- Eclipse 调优及使用小细节
- Docker之Weave实现Docker多宿主机互联-yellowcong
- [poj2096][动态规划DP]Collecting Bugs