#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
template<class T>
class List{
public:
struct node{
T data;
node* next;
node(){ next = NULL;}
};
node *head, *tail;
List(){ head = new node, tail = NULL;}
node* begin(){ return head->next;}
node* end(){ return NULL;}
void push_front(T data){
node *p = new node;
p->data = data, p->next = head->next, head->next = p;
if(tail == NULL)
tail = p;
}
void push_back(T data){
node *p = new node;
p->data = data;
if(tail == NULL) {
tail = p;
head->next = tail;
}
else
tail->next = p, tail = p;
}
void pop_front(){
if(head->next == NULL){
puts("runtime error");
return;
}
node* p = head->next;
head->next = p->next;
delete p;
if(head->next == NULL)tail = NULL;
}
T front(){
if(head->next == NULL){
puts("runtime error");
exit(0);
}
return head->next->data;
}
T back(){
if(tail == NULL){
puts("runtime error");
exit(0);
}
return tail->data;
}
void print(){
node *L = head->next;
while(L){
cout << L->data << endl;
L = L->next;
}
}
void clear(){
node* L = head->next;
while(L){
node* p = L;
L = L->next;
delete p;
}
head->next = NULL;
tail = NULL;
}
virtual ~List(){clear(); delete head;}
struct iterator{
node *p;
iterator(){p = NULL;}
iterator(node* q){ p = q;}
node* operator ++(){p = p->next; return p;}
iterator& operator = (node* q){p = q; return *this;}
bool operator != (node* q){ return p != q;}
bool operator ==(node* q){ return p == q;}
T operator *(){ return p->data;}
};
};
int main(){
List<int>L;
for(int i = 0; i < 5; i++) L.push_front(i);
for(int i = 0; i < 5; i++) L.push_back(i+5);
// for(int i = 0; i < 20; i++) L.pop_front();//pop的太多
for(int i = 0; i < 5; i++) L.push_front(i);
List<int>::iterator it;
for(it = L.begin(); it != L.end(); ++it){
cout << *it << " ";
}
puts("");
for(List<int>::iterator iter = L.begin(); iter != L.end(); ++iter){
cout << *iter << " ";
}
return 0;
}
STL_迭代器_单向链表
最新推荐文章于 2024-05-21 14:16:35 发布