双链 头文件 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");
}