链表实现-c++

链表是比较常见的数据结构了,没有特别需要难理解的地方,主要是实现的时候注意细节就好了。

废话不多说,话都在酒(代码)里。

#include<iostream>
#include<cassert>
using namespace std;
 
template<class T>
class Node
{
	T e;
	Node* next;
	Node() : next(nullptr) {}
	Node(T elem) : e(elem) {}
	Node(T elem,Node* ne) : e(elem), next(ne) {}
};
 
template<class T>
class LinkList
{
private:
	Node<T>* head;
	int size;
 
public:
	LinkList()
	{
		head = new Node<T>();
		size = 0;
	}
 
	int  get_size()
	{
		return size;
	}
 
	bool isempty()
	{
		return size == 0;
	}
 
	void insert(int index, T e)
	{
		assert(index >= 0 && index <= size);
		Node<T>* pre = head;
		for (int i = 0; i < index; i++)
		{
			pre = pre->next;
		}
 
		pre->next = new Node<T>(e, pre->next);
 
		++size;
	}
 
	void insert_front(T e)
	{
		insert(0, e);
	}
 
	void insert_back(T e)
	{
		insert(size, e);
	}
 
	T get(int index)
	{
		assert(index >= 1 && index <= size);
		Node<T>* cur = head;
		for (int i = 0; i < index; i++)
		{
			cur = cur->next;
		}
		return cur->e;
	}
 
	T get_front()
	{
		return get(1);
	}
 
	T get_back()
	{
		return get(size);
	}
 
	void set(int index, T e)
	{
		assert(index >= 1 && index <= size);
		Node<T>* cur = head;
		for (int i = 0; i < index; i++)
		{
			cur = cur->next;
		}
		cur->e = e;
	}
 
	void set_front(T e)
	{
		set(1, e);
	}
 
	void set_back(T e)
	{
		set(size, e);
	}
 
	T remove(int index)
	{
		assert(index >= 1 && index <= size);
		Node<T>* cur = head;
		for (int i = 0; i < index - 1; i++)
		{
			cur = cur->next;
		}
		T tem = cur->next->e;
		cur->next = cur->next->next;
		--size;
		return tem;
	}
 
	T remove_front()
	{
		remove(1);
	}
 
	T remove_back()
	{
		remove(size);
	}
 
	void removeElem(T e)
	{
		Node<T>* cur = head;
		while (cur->next)
		{
			if (cur->next->e == e) break;
			cur = cur->next;
		}
 
		if (cur->next)
		{
			cur->next = cur->next->next;
			--size;
		}
	}
 
	bool contains(T e)
	{
		Node<T>* cur = head;
		while (cur->next)
		{
			cur = cur->next;
			if (cur->e == e) return true;
		}
		return false;
	}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值