c++ 封装的单链表

温故知新:

以前学习c++时写的链表

复习一下


#include <iostream>
using namespace std;


template<typename T=int>
class List
{
private:
	struct Node
	{
		T data;
		Node* next;
		Node(const T& d):data(d),next(NULL){}
	};
	Node* head;
	int n;
public:
	List():head(NULL),n(0)
	{ }
	void clear()
	{
		Node* p = head;
		while(p)
		{
			Node* q = p->next;
			delete p;
			p = q;
		}
		head = NULL;
		n = 0;
	}
	~List()
	{
		clear();
	}
	void travel()const
	{
		Node* p = head;
		while( p )
		{
			cout << p->data << ' ';
			p = p->next;
		}
		cout << endl;
	}
	Node* & getp(int pos)//按索引查找 
	{
		if(pos<0||pos>n) 
			pos=n;//throw xxx;
		if(pos==0) 
			return head;
		Node* p = head;
		for(int i=1; i<pos; i++)// i 为索引,i等于几,p 就指向对应的那个位置
			p = p->next;
		return p->next;
	}
	Node* const & getp(int pos)const
	{
		return const_cast<List*>(this)->getp(pos);
	}
	void insert(const T& d, int pos=-1)
	{
		Node* & r = getp(pos);
		Node* p = new Node(d);
		p->next = r;
		r = p;
		++n;
	}
	int find(const T& d, int pos=0)const
	{
		Node* p = getp(pos);
		while(p)
		{
			if(p->data==d) 
				return pos;//找到了
			p = p->next;
			++pos;
		}
		return -1;//没找到
	}
	bool erase(const T& d, int pos=0)
	{
		if( (pos=find(d,pos))==-1 )
			return false;//没找到
		Node* & r = getp(pos);
		Node* p = r;
		r = r->next;
		delete p;
		p = NULL;
		--n;
		return true;
	}
	bool update(const T& oldd, const T& newd, int pos=0)
	{
		if( (pos=find(oldd,pos))==-1 ) 
			return false;//没找到
		getp(pos)->data = newd;
		return true;
	}
	int size()const
	{
		return n;
	}
	bool empty()const
	{
		return n==0;
	}
	const T& front()const throw(int)
	{
		if(empty()) 
			throw 1;
		return head->data;
	} 
	const T& back()const throw(int)
	{
		if(empty()) 
			throw 2;
		return getp(n-1)->data;
	}
	void push_front(const T& d)
	{
		insert(d,0);
	}
	void push_back(const T& d)
	{
		insert(d);
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值