单链表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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值