dList.h
#pragma once
#include <iostream>
#include <assert.h>
using namespace std;
typedef int DataType;
struct ListNode
{
ListNode(DataType d = 0, ListNode* next = NULL, ListNode* prev = NULL)
:_next(next), _prev(prev), _data(d)
{}
ListNode* _next;
ListNode* _prev;
DataType _data;
};
inline void Swap(ListNode*& pn1, ListNode*& pn2)
{
ListNode* tmp = pn1;
pn1 = pn2;
pn2 = tmp;
}
class List
{
typedef ListNode Node;
public:
List()
:_head(NULL), _tail(NULL)
{}
List(const List& l)
{
if (l._head == NULL)
{
List();
return;
}
if (l._head == l._tail)
{
_head = _tail = new Node(l._head->_data);
if (l._head->_next != NULL)
_head->_next = _head->_prev = _head;
}
Node* cur = _head = new Node(l._head->_data);
Node* l_cur = l._head->_next;
while (l_cur != l._tail)
{
cur->_next = new Node(l_cur->_data, NULL, cur);
cur = cur->_next;
l_cur = l_cur->_next;
}
cur->_next = new Node(l_cur->_data, NULL, cur);
if (l._tail->_next != NULL)
{
if (l._tail->_next == l._head)
{
_tail->_next = _head;
_head->_prev = _tail;
}
else
{
l_cur = l._head;
cur = _head;
while (l_cur != l._tail->_next)
{
l_cur = l_cur->_next;
cur = cur->_next;
}
_tail->_next = cur;
}
}
}
List& operator=(const List& l)
{
List newlist(l);
Swap(newlist);
return *this;
}
~List()
{
while (_head != _tail)
{
Node* tmp = _head;
_head = _head->_next;
delete tmp;
}
delete _tail;
}
void PushBack(DataType x)
{
if (_tail != NULL)
{
_tail->_next = new Node(x, _tail->_next, _tail);
_tail = _tail->_next;
}
else
_tail = _head = new Node(x);
}
void PopBack()
{
if (_tail = NULL)
return;
Node* oldTail = _tail;
_tail = _tail->_prev;
_tail->_next = oldTail->_next;
delete oldTail;
}
void PushFront(DataType x)
{
if (_head == NULL)
_head = _tail = new Node(x);
else
{
_head->_prev = new Node(x, _head, _head->_prev);
_head = _head->_prev;
}
}
void PopFront()
{
if (_head = NULL)
return;
Node* oldHead = _head;
_head = _head->_next;
_head->_prev = oldHead->_prev;
delete oldHead;
}
void Insert(Node* pos, DataType x)
{
assert(pos);
pos->_prev = pos->_prev->_next = new Node(x, pos, pos->_prev);
}
void Erase(Node* pos)
{
pos->_prev->_next = pos->_next;
pos->_next->_prev = pos->_prev;
delete pos;
}
Node* Find(DataType x)
{
Node* ret = _head;
while (ret->_data != x && ret != _tail)
{
ret = ret->_next;
}
if (ret->_data == x)
return ret;
return _tail->_data == x ? _tail : NULL;
}
void Reverse()
{
if (_head == NULL || _head == _tail)
return;
Node* cur = _head;
while (cur != _tail)
{
::Swap(cur->_next, cur->_prev);
cur = cur->_prev;
}
::Swap(cur->_next, cur->_prev);
::Swap(_tail, _head);
}
void Swap(List& l)
{
::Swap(_head, l._head);
::Swap(_tail, l._tail);
}
private:
Node* _head;
Node* _tail;
};