单链表c++简单模板实现
简单的单链表模板实现:
#include<iostream> using namespace std; template <typename T> class List{ public: //构造函数 List():head(NULL), len(0){} //析构函数 ~List(){ clear(); } //判断链表是否为空 bool empty()const{ return head == NULL; } //返回链表元素的个数 int size()const{ return len; } //遍历链表 void travel()const{ if(empty()) return ; Node* p = head; while(p != NULL){ cout << p->data << ' '; p = p->next; } cout << endl; } //向任意位置插入元素 void insert(const T& d, int pos){ Node* p = new Node(d); Node*& pn = getptr(pos); p->next = pn; pn = p; ++len; } //从链表头部插入 List& push_front(const T& d){ insert(d, 0); return *this; } //从链表尾部插入 List& push_back(const T& d){ insert(d, size()); return *this; } //返回头部元素 T front()const{ if(empty()) return ; return head->data; } //返回尾部元素 T back()const{ if(empty()) return ; Node*& pn = getptr(size()-1); return pn->data; } //删除指定位置元素 void erase(int pos){ if(pos < 0 || pos >= size()) throw "invalid"; Node*& pn = getptr(pos); Node* p = pn; pn = pn->next; delete p; --len; } //删除表头元素 void pop_front(){ erase(0); } //删除尾部元素 void pop_back(){ erase(size()-1); } private: struct Node{ T data; Node* next; Node(T d):data(d), next(NULL){} }; Node* head; int len; //释放动态内存,供析构函数调用 void clear(){ if(head == NULL) return ; while(head != NULL){ Node* p = head; delete p; head = head->next; } } //得到指向插入位置的指针 Node*& getptr(int pos){ if(pos < 0 || pos > size()) throw "invalid"; if(pos == 0) return head; Node* p = head; for(int i=1; i<pos; i++){ p = p->next; } return p->next; } }; //测试代码 int main() { List<int> li; li.push_back(2); li.push_back(3); li.push_front(1); li.insert(0, 0); li.travel(); li.pop_back(); li.travel(); li.pop_front(); li.travel(); return 0; }