c++模板实现双向链表:
#include <iostream>
#include <assert.h>
using namespace std;
template<typename T>
struct ListNode
{
T _data;
ListNode<T>* _prev;
ListNode<T>* _next;
ListNode()
:_next(NULL)
, _prev(NULL)
{}
};
template<typename T>
class List
{
typedef ListNode<T> Node;
public:
List()
:_head(NULL)
,_tail(NULL)
{}
List<T>& operator=(List<T> list)
{
swap(_head, list._head);
swap(_tail, list._tail);
return *this;
}
List( const List<T>& s)// ?????
:_tail(NULL)
, _head(NULL)
{
Node* cur = s._head;
while (cur)
{
PushBack(cur->_data);
cur = cur->_next;
}
}
void PushBack(const T& x)//1、空链表2、有多个元素
{
if (_tail == NULL)//空链表
{
_head = _tail = new Node;
_tail->_data = x;
_head->_next = NULL;
_head->_prev = NULL;
}
else//多个元素
{
Node* p = new Node;
p->_data = x;
_tail->_next = p;
p->_prev = _tail;
_tail = p;
_head->_prev = NULL;
_tail->_next = NULL;
}
}
void PopBack()//1、空链表2、一个元素3、多个元素
{
if (NULL == _head)
{
_head = new Node(x);
}
else if (_head == _tail)//一个结点
{
delete _tail;
_tail = _head = NULL;
}
else//多个结点
{
Node* tmp = _tail->_prev;
delete[] _tail;
_tail = tmp;
_tail ->_next= NULL;
}
}
void PushFront(const T&x)//头插(1、空2、不空)
{
Node* newnode = new Node(x);
if (_head == NULL)
{
newnode->_next = NULL;
newnode->_prev = NULL;
_head = _tail = newnode;
}
else
{
Node* tmp = _head;
newnode->_next = tmp;
tmp->_prev = newnode;
_head = newnode;
newnode->_prev = NULL;
}
}
void PopFront()
{
Node* tmp = _head->_next;
delete[] _head;
_head = tmp;
}
void Insert(Node* pos, T x)//pos前面插
{
assert(pos);
Node* newnode = new Node(x);
Node* tmp = pos->_prev;//保存pos位置前一个节点地址
if (tmp)//pos不是第一个节点
{
tmp->_next = newnode;//将新节点和前一个连接
newnode->_prev = tmp;
}
else//pos是第一个节点
{
_tail = newnode;
newnode->_prev = NULL;
}
newnode->_next = pos;
pos->_prev = newnode;
}
~List()//析构函数
{
Node* tmp = _head;
Node* cur = NULL;
while (tmp)
{
cur = tmp->_next;
delete[] tmp;
tmp = cur;
}
}
Node* Find(const T &x)
{
Node* cur = _head;
while (cur)
{
if (cur->_data == x)
{
return cur;
}
cur = cur->_next;
}
}
void Erase(Node* pos)//1、空2、删头3、删尾4、删中间
{
assert(pos);
if (NULL == _head)//空
{
return;
}
else if (_head == _tail)//一个元素
{
assert(_head != pos);
delete[] _head;
_head = _tail = NULL;
}
else if (_head == pos)//pos为头
{
Node* cur = _head->_next;
delete[] _head;
_head = cur;
cur->_prev = NULL;
}
else if (_tail == pos)
{
Node* cur = _tail->_prev;
delete[] _tail;
_tail = cur;
cur->_next = NULL;
}
else
{
Node* prev = pos->_prev;
Node* next = pos->_next;
delete[] pos;
prev->_next = next;
next->_prev = prev;
}
}
void Print()
{
Node* cur = _head;
while (cur != NULL)
{
cout << cur->_data<< endl;
cur = cur->_next;
}
}
private:
Node* _tail;
Node* _head;
};
int main()
{
List<int> a;
a.PushBack(1);
a.PushBack(2);
a.PushBack(3);
a.PushBack(4);
a.PushBack(5);
/*a.Erase(a.Find(3));
a.Erase(a.Find(2));
a.Erase(a.Find(1));*/
List<int> b(a);
b.PushBack(4);
b.PushBack(5);
b = a;
b.Print();
system("pause");
return 0;
}