数据结构与算法之单链表 自己实现STL list模板类

来源:互联网 发布:淘宝网上银行支付 编辑:程序博客网 时间:2024/05/19 20:59

自己写的一个简单的单链表模板类,类似STL功能,不过是单链表,与真正的STL肯定很大区别,只是自己模仿一下而已。

#include<iostream>using namespace std;template<class T>struct node{T element;node* next;};template<class T>class my_list{public:my_list();my_list(int n);~my_list();int size()const;bool empty()const;T& operator[](int n)const;//取第i个值node<T>* insert(int i, const T& new_node);//插入node<T>* erase(int i);//删除node<T>* push_back(const T& new_node);//末尾插入node<T>* push_front(const T& new_node);//前面插入private:int m_size;node<T>*  m_head;};template<class T>my_list<T>::my_list(){m_head  = NULL;m_size = 0;}template<class T>my_list<T>::my_list(int n){m_size = 0;m_head = NULL;node<T> *p = new node<T>;m_head = p;while(--n){node<T> *q = new node<T>;p->next = q;p = q;m_size++;}m_size++;p->next = NULL;}template<class T>my_list<T>::~my_list(){if(m_head != NULL){node<T> *t = m_head;while(m_head != NULL){t = m_head;m_head = m_head->next;delete t;}}m_head = NULL;m_size = 0;}template<class T>int my_list<T>::size()const{return m_size;}template<class T>bool my_list<T>::empty()const{if(m_size == 0)return true;elsereturn false;}template<class T>T& my_list<T>::operator[](int n)const{node<T> *p = m_head;while(p != NULL && n--){p = p->next;}return p->element;}template<class T>node<T>* my_list<T>::push_back(const T& new_node){node<T>* p = m_head;if(p == NULL){m_head = new node<T>;m_head->element = new_node;m_head->next = NULL;m_size++;}else{node<T> *t = p;while(p != NULL){t = p;p = p->next;}t->next = new node<T>;t->next->element = new_node;t->next->next = NULL;m_size++;}return m_head;}template<class T>node<T>* my_list<T>::push_front(const T& new_node){node<T> *p = m_head;if(p == NULL){m_head = new node<T>;m_head->element = new_node;m_head->next = NULL;m_size++;}else{m_head = new node<T>;m_head->element = new_node;m_head->next = p;m_size++;}return m_head;}template<class T>node<T>* my_list<T>::insert(int i, const T& new_node){if(i == 0){return push_front(new_node);}if(i == m_size){return push_back(new_node);}if(i > 0 && i < m_size){node<T>* p = m_head;node<T>* t = p;while(--i){t = p;p = p->next;}node<T> *q = new node<T>;q->element = new_node;q->next = p;t->next = q;m_size++;}return m_head;}template<class T>node<T>* my_list<T>::erase(int i){if(empty())return NULL;if(i == 0){node<T>* p = m_head;m_head = m_head->next;delete p;m_size--;}if(i > 0 && i < m_size){node<T>* p = m_head;node<T>* t = p;while(--i){t = p;p = p->next;}t->next = p->next;delete p;m_size--;}return m_head;}int main(){my_list<int> a;int i = 0;for(i = 9; i >= 0; i--){a.push_back(i);}for(i = 10; i < 20; i++){a.push_front(i);}a.insert(10,-1);a.erase(8);for(i = 0; i < a.size(); i++){cout<<a[i]<<' ';}return 0;}


原创粉丝点击