STL_迭代器_单向链表

7 篇文章 0 订阅
#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值