您的位置:首页 > 游戏 > 游戏 > 靖江网站推广_网站设计与制作平台_百度代理服务器_5118

靖江网站推广_网站设计与制作平台_百度代理服务器_5118

2025/7/15 10:26:40 来源:https://blog.csdn.net/WYF_111501/article/details/147100755  浏览:    关键词:靖江网站推广_网站设计与制作平台_百度代理服务器_5118
靖江网站推广_网站设计与制作平台_百度代理服务器_5118

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sstream>
#include <vector>
#include <memory>using namespace std;class myException:public exception{private:public:const char* what()const noexcept{return "越界访问";}
};
template <class T>
class myList{
public:struct Node{T val;Node* next;Node* prev;};class iterator{private:Node* ptr;public:iterator(Node* ptr=NULL);T& operator*();bool operator!=(const iterator& r);iterator& operator++(int);iterator& operator++();};myList();void push_back(const T& val);myList& operator<<(const T& val);T& operator[](int index);int size();iterator begin();iterator end();
private:Node* head; //真正的链表(链表头头节点)Node* tail; // 链表尾节点int count;
};
//===========================================
//迭代器代码
template <typename T>
myList<T>::iterator::iterator(Node* ptr):ptr(ptr){}template <typename T>
T& myList<T>::iterator::operator*(){return ptr->val;
}template <typename T>
bool myList<T>::iterator::operator!=(const iterator& r){return ptr!=r.ptr;
}template <typename T>
typename myList<T>::iterator& myList<T>::iterator::operator++(int){if(ptr==NULL){throw myException();}ptr=ptr->next;return *this;
}template <typename T>
typename myList<T>::iterator& myList<T>::iterator::operator++(){if(ptr==NULL){throw myException();}ptr=ptr->next;return *this;
}template <typename T>
typename myList<T>::iterator myList<T>::begin(){iterator it(head->next);return it;
}template <typename T>
typename myList<T>::iterator myList<T>::end(){iterator it(tail->next);return it;
}template <typename T>
myList<T>::myList(){head = new Node;head->next = NULL;head->prev = NULL;tail = head; // 只有头节点的情况下,尾节点即使头节点count = 0;
}template <typename T>
void myList<T>::push_back(const T& val){Node* newnode = new Node;newnode->val = val;newnode->next = NULL;newnode->prev = tail;tail->next = newnode;tail = newnode;count ++;
}template <typename T>
myList<T>& myList<T>::operator<<(const T& val){push_back(val);// return 0return *this;
}template <typename T>
T& myList<T>::operator[](int index){if(index<0 || index>=count){throw myException();}Node* p = head->next;for(int i=0;i<index;i++){p = p->next;}return p->val;
}template <typename T>
int myList<T>::size(){return count;
}int main(int argc,const char** argv){myList<int> l;l << 1 << 3 << 5 << 7 << 9;try{cout << l[5] << endl;}catch(const myException& e){cout << "捕获异常:" << e.what() <<endl;} try{myList<int>::iterator it=l.end();++it;}catch(const myException& e){cout << "捕获异常:" << e.what() <<endl;} return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com