#pragma once#includeusing namespace std;typedef int DataType;//结构体的定义struct Node{ Node(const DataType& d) :_data(d) , _prev(NULL) , _next(NULL) {} Node* _next; Node* _prev; DataType _data;};//双向链表类的定义class DList{friend ostream& operator<<(ostream& os,DList& d);public: DList()//构造函数 :_head(NULL) ,_tail(NULL) {} ~DList()//析构函数 { Node* cur = _head; while (cur) { Node* del = cur; cur = cur->_next; delete del; } }public: void PushBack(const DataType& d);//后插 void PushFront(const DataType& d);//前插 void PopBack();//后出 void PopFront();//前出 void Find(const DataType& d);//查找 void Insert(const DataType& d);//在指定位置插入 void BubbSort();//冒泡排序 void Reverse();//逆序 void Remove(const DataType& d);//删除指定的元素 void RemoveAll(const DataType& d);//删除所有指定的元素 void Erase(Node* pos);//删除指定节点private: Node* _head;//头指针 Node* _tail;//尾指针};
#include"DList.h"
ostream& operator<<(ostream& os,DList& d)//输出运算符的重载
{
Node*cur = d._head;
while (cur)
{
os << cur->_data <<"<=>";
cur = cur->_next;
}
os <<"over";
return os;
}
void DList::PushBack(const DataType& d)
{
Node* newNode = new Node(d);
if (_head == NULL)
{
_head = newNode;
_tail = _head;
}
else
{
_tail->_next = newNode;
newNode->_prev = _tail;
_tail = newNode;
}
}
void DList::PushFront(const DataType& d)
{
Node* newNode = new Node(d);
if (_head == NULL)
{
_head = newNode;
_tail = _head;
}
else
{
newNode->_next = _head;
_head->_prev = newNode;
_head = newNode;
}
}
void DList::PopBack()
{
if (_head == NULL)
{
return;
}
else if (_head == _tail)
{
delete _head;
_head = NULL;
_tail = NULL;
}
else
{
_tail = _tail->_prev;
delete _tail->_next;
_tail->_next = NULL;
}
}
void DList::PopFront()
{
if (_head = NULL)
{
return;
}
else if (_head == _tail)
{
delete _head;
_head = NULL;
_tail = NULL;
return;
}
else
{
Node* del = _head;
_head = _head->_next;
_head->_prev = NULL;
delete del;
}
}
#include"DList.h"
void test1()
{
DList l1;
l1.PushBack(1);
l1.PushBack(2);
l1.PushBack(3);
l1.PushBack(4);
cout << l1 << endl;
l1.PopBack();
l1.PopBack();
cout << l1 << endl;
l1.PopBack();
l1.PopBack();
l1.PopBack();
cout << l1 << endl;
}
int main()
{
test1();
getchar();
return 0;
}