typedef int DataType;
struct Node
{
struct Node* _pNext;
struct Node* _pPre;
DataType _data;
Node(const DataType& data = DataType())
: _pNext(NULL)
, _pPre(NULL)
, _data(data)
{}
};
class List
{
typedef Node* PNode;
public:
List()
: _pHead(NULL)
{}
List(const DataType* array, size_t size)
{
for (size_t i = ; i < size; ++i)
{
PushBack(array[i]);
}
}
List(const List& L)
{
_pHead = new Node;
PNode ptail = _pHead->_pNext;
while (ptail != _pHead)
{
PushBack(ptail->_data);
ptail = ptail->_pNext;
}
}
List& operator=(const List& s)
{
if (this == &s)
{
return *this;
}
this->_pHead = new Node;
PNode ptail = _pHead->_pNext;
while (ptail != _pHead)
{
PushBack(ptail->_data);
ptail = ptail->_pNext;
}
}
~List() //逆向销毁
{
Clear();//清空链表中的元素,表头结点还在
delete _pHead;
_pHead = NULL;
}
void PushBack(const DataType& data)
{
PNode ptail = _pHead->_pPre;
PNode pNewNode = new Node(data);
ptail->_pNext = pNewNode;
pNewNode->_pNext = _pHead;
pNewNode->_pPre = ptail;
_pHead->_pPre = pNewNode;
}
void PopBack()
{
PNode ptail = _pHead->_pPre;
ptail->_pPre->_pNext = _pHead;
_pHead->_pPre = ptail->_pPre;
delete ptail;
}
void PushFront(const DataType& data)
{
PNode ptail = new Node(data);
ptail->_pNext = _pHead->_pNext;
_pHead->_pNext->_pPre = ptail;
ptail->_pPre = _pHead;
_pHead->_pNext = ptail;
}
void PopFront()
{
if (_pHead->_pNext == _pHead)
return;
else
{
PNode ptail = _pHead->_pNext;
_pHead->_pNext = ptail->_pNext;
ptail->_pNext->_pPre = _pHead;
delete ptail;
}
}
// 返回插入的新节点
Node* Insert(Node* pos, DataType data)
{
PNode ptail = pos->_pPre;
PNode pNewNode = new Node(data);
pNewNode->_pNext = ptail;
ptail->_pPre = pNewNode;
pos->_pNext = pNewNode;
pNewNode->_pPre = pos;
}
// 返回删除节点的下一个位置
Node* Erase(Node* pos)
{
pos->_pPre->_pNext = pos->_pNext;
pos->_pNext->_pPre = pos->_pPre;
delete pos;
}
size_t Size()const
{
int count = ;
PNode ptail = _pHead->_pNext;
while (ptail != _pHead)
{
count++;
ptail = ptail->_pNext;
}
return count;
}
bool Empty()const
{
return _pHead->_pNext - _pHead;
}
void Clear()
{
PNode ptail = _pHead->_pNext;
while (ptail != _pHead)
{
_pHead->_pNext = ptail->_pNext;
delete ptail;
ptail = _pHead->_pNext;
}
ptail->_pPre = _pHead;
}
friend ostream& operator<<(ostream& _cout, const List& s)
{
PNode ptail = _pHead->_pNext;
while (ptail != _pHead)
{
cout << s._pHead->_data << ;
ptail = ptail->_pNext;
}
return _cout;
}
private:
Node* _pHead;
};
int main(void)
{
size_t i;
List l1;
l1.PushBack();
l1.PushBack();
l1.PushBack();
l1.PushBack();
l1.PopBack();
cout << l1 << endl;
return ;
}