c++双链表附测试

双链 头文件 list.h

#ifndef  _LIST_
#define _LIST_
#include<iostream>
#include<vector>
using namespace std;

template<class T>
class Node
{
public:
	Node() :value(0), next(NULL), prev(NULL) {}
	Node(const T& value1) :value(value1), next(NULL), prev(NULL) {}
	~Node()
	{

	}
	T value;
	Node<T>* next;
	Node<T>* prev;
};

template<class T>
class List
{
public:
	List():head(NULL),length(0){}
	List(const vector<T>&vec);
	~List();
	void Delete(const T&value);
	void Insert(int  position,T value);
	bool search(const T&value1);
	void print()const;

private:
	Node<T>* head;
	int length;
};

template<class T>
void List<T>::print()const {
	Node<T>* cur = head;
	while (cur->next != head) {
		cout << cur->next->value << " ";
		cur = cur->next;
	}
}

template<class T>
List<T>::List(const vector<T>& vec) {
	head = new Node<T>();
	Node<T>* cur = head;
	length = vec.size();
	for (int i = 0; i < vec.size(); i++) {
		cur->next = new Node<T>(vec[i]);
		cur->next->prev = cur;
		cur = cur->next;
	}
	cur->next = head;
	head->prev = cur;
}

template<class T>
List<T>::~List() {
	this->length = 0;
	Node<T>* cur = new Node<T>();
	Node<T>* cur1 = head->next;
	while (cur != head) {
		cur =cur1 ;
		cur1 = cur1->next;
		delete cur;
	}
	delete head;
}

template<class T>
void List<T>::Delete(const T&value) {
	this->length--;
	Node<T>* cur = head->next;
	Node<T>* cur1 = new Node<T>();
	while (cur != head) {
		if (cur->value == value) {
			if (cur != head) {
				cur->prev->next = cur->next;
				cur->next->prev = cur->prev;
				cur1 = cur;
				cur = cur->next;
				delete cur1;
				continue;
			}
		}
		else
			cur = cur->next;
	}
}

template<class T>
void List<T>::Insert(int position,T value) {
	this->length++;
	Node<T>* cur = head;
	Node<T>* cur1 = new Node<T>(value);
	Node<T>* cur2 = new Node<T>();
	for (int i = 1; i <= position; i++) {
		cur = cur->next;
	}
	cur2 = cur->next;
	cur1->next = cur->next;
	cur1->prev = cur;
	cur->next = cur1;
	cur2->prev = cur2;
}

template<class T>
bool List<T>::search(const T&value1) {
	Node<T>* cur = head->next;
	while (cur != head) {
		if (cur->value == value1)
			return true;
	}
	else
		return false;
}
#endif // !_LIST_

测试 main.cpp

#include"list.h"
int main()
{
	vector<int> vec;
	int i;
	while (cin >> i) {
		vec.push_back(i);
	}
	List<int> list(vec);
	list.Insert(2, 10);
	int p;
	cin >> p;
	list.Delete(p);
	list.print();
	list.search(p);
	system("pause");
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值