您的位置:首页 > 编程语言 > C语言/C++

C++之模板实现list

2017-12-04 17:13 288 查看
#include <iostream>
#include <assert.h>

using namespace std;

template<typename T>
struct ListNode
{
ListNode(const T& data = T())
: _pNext(NULL)
, _pPre(NULL)
, _data(data)
{}

ListNode* _pNext;
ListNode* _pPre;
T _data;
};

template <typename T>
class List
{
typedef ListNode<T> Node;
typedef Node* PNode;

public:
List()
{
CreateListHead();
}

List(T* array, size_t size)
{
CreateListHead();
for (size_t i = 0; i < size; i++)
{
PushBack(array[i]);
}
}
List(const List<T>& l)
{
_pHead = l._pHead;
PNode pcur = l._pHead;
while (pcur->_pNext != l._pHead)
{
PushBack(pcur->_pNext->_data);
pcur = pcur->_pNext;
}
}
List<T>& operator=(const List<T>& l)
{
if (this != &l)
{
this->Clear();
PNode pcur = l._pHead->_pNext;
while (pcur != l._pHead)
{
PushBack(pcur->_data);
pcur = pcur->_pNext;
}
}
return *this;
}
~List()
{
Clear();
delete _pHead;
_pHead = NULL;
}
///////////////////////////////////////////////

void PushBack(const T& data)
{
PNode ptail = new Node(data);
_pHead->_pPre->_pNext = ptail;
ptail->_pNext = _pHead;
ptail->_pPre = _pHead->_pPre;
_pHead->_pPre = ptail;
}
void PopBack()
{
if (Empty())
return;
PNode ptail = _pHead->_pPre;
ptail->_pPre->_pNext = _pHead;
_pHead->_pPre = ptail->_pPre;

delete ptail;
}
void PushFront(const T& data)
{
PNode pNewnode = new Node(data);
pNewnode->_pNext = _pHead->_pNext;
pNewnode->_pPre = _pHead;
_pHead->_pNext->_pPre = pNewnode;
_pHead->_pNext = pNewnode;
}
void PopFront()
{
if (Empty())
return;
PNode pcur = _pHead->_pNext;
_pHead->_pNext = _pHead->_pNext->_pNext;
_pHead->_pNext->_pPre = _pHead;
delete pcur;
}
PNode Insert(PNode pos, const T& data)
{
assert(pos);
PNode pNewnode = new Node(data);
PNode p1 = pos;
pNewnode->_pNext = p1;
pNewnode->_pPre = p1->_pPre;
p1->_pPre->_pNext = pNewnode;
p1->_pPre = pNewnode;

}
PNode Erase(PNode pos)
{
assert(pos);
PNode p2 = pos;
p2->_pPre->_pNext = p2->_pNext;
p2->_pNext->_pPre = p2->_pPre;

delete p2;
}

size_t Size()
{
size_t count = 0;
PNode pcu
97dd
r = _pHead;
while (pcur->_pNext != _pHead)
{
count++;
pcur = pcur->_pNext;
}
return count;
}
// 将链表中的结点清空
void Clear()
{
PNode pcur = _pHead->_pNext;
while (pcur != _pHead)
{
PNode _next = pcur->_pNext;
delete pcur;
pcur = _next;
}
_pHead->_pNext = _pHead;
_pHead->_pPre = _pHead;
}
bool Empty()const
{
if (_pHead->_pNext == _pHead)
return true;
else
return false;
}
void Print()
{
PNode pcur = _pHead->_pNext;
while (pcur != _pHead)
{
cout << pcur->_data << " ";
pcur = pcur->_pNext;
}
cout << endl;
}
private:
void CreateListHead()
{
_pHead = new Node;
_pHead->_pNext = _pHead;
_pHead->_pPre = _pHead;
}

private:
PNode _pHead;
};

void Test1()//尾部插入和删除
{
//插入
List<int> l;
l.PushBack(1);
l.Print();
l.PushBack(2);
l.Print();
l.PushBack(3);
l.Print();
l.PushBack(4);
l.Print();

//删除
l.PopBack();
l.Print();
l.PopBack();
l.Print();
l.PopBack();
l.Print();
}

int main()
{
Test1();
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: