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

C++实现双向链表

2016-04-09 13:37 513 查看
#include <iostream>

using namespace std;

typedef int DateType;

class LinkNode

{

friend class List;

public:

LinkNode( const DateType& x)

:_data(x)

,_prev(NULL)

,_next(NULL)

{}

private:

DateType _data;

LinkNode* _prev;

LinkNode* _next;

};

class List

{

private:

LinkNode* _head;

LinkNode* _tail;

public:

List()

:_head(NULL)

,_tail(NULL)

{}

void Print()//打印链表

{

if(_head == NULL)//空链表

{

return;

}

else//非空链表

{

LinkNode* tmp = _head;

while(tmp)

{

cout<<tmp->_data<<"->";

tmp = tmp->_next;

}

cout<<endl;

}

}

void PushFront(const DateType& x)//头插

{

if(_head == NULL)

{

LinkNode *tmp = new LinkNode(x);

_head = tmp;

_tail = tmp;

}

else

{

LinkNode *tmp = new LinkNode(x);

tmp->_prev = NULL;

tmp->_next = _head;

tmp->_next->_prev = tmp;

_head = tmp;

}

}

void PopFront()//头删

{

if(_head == NULL)

{

return;

}

else

{

if(_head == _tail)

{

delete _head;

_head = NULL;

_tail = NULL;

}

else//两个及两个以上的节点

{

LinkNode* begin = _head;

_head->_next->_prev = NULL;

_head = _head->_next;

delete begin;

}

}

}

void PushBack(const DateType& x)//尾插

{

if(_head == NULL)//空链表

{

LinkNode* tmp = new LinkNode(x);

_head = tmp;

_tail = tmp;

}

else//非空链表

{

LinkNode* tmp = new LinkNode(x);

_tail->_next = tmp;

tmp->_prev = _tail;

_tail = tmp;

}

}

void PopBack()//尾删

{

if(_head == NULL)//空链表

return;

else

{

if(_head == _tail)//一个节点

{

delete _head;

_head =NULL;

_tail = NULL;

}

else//多个节点

{

LinkNode* tmp = _head;

while(tmp->_next != _tail)

{

tmp = tmp->_next;

}

delete tmp->_next;

tmp->_next =NULL;

}

}

}

LinkNode* Find(const DateType& x)

{

LinkNode* begin = _head;

while(begin)

{

if(begin->_data == x)

return begin;

begin = begin->_next;

}

return NULL;

}

void Insert(LinkNode* pos, const DateType& x)//插入

{

if(pos == NULL)

return;

if(pos == _tail)

{

LinkNode* tmp = new LinkNode(x);

_tail->_next = tmp;

tmp->_prev = _tail;

_tail = tmp;

}

else

{

LinkNode* tmp = new LinkNode(x);

tmp->_next = pos->_next;

pos->_next->_prev = tmp;

pos->_next = tmp;

tmp->_prev = pos;

}

}

void Erase(LinkNode* del)//删除节点

{

if(del)

{

return;

}

if(del == _head)

{

LinkNode* tmp = _head;

_head = _head->_next;

_head->_prev = NULL;

delete tmp;

}

if(del == _tail)

{

LinkNode* tmp = _tail;

_tail = _tail->_prev;

_tail->_next = NULL;

delete tmp;

}

else

{

LinkNode* tmp = del;

tmp->_next->_prev = tmp->_prev;

del->_prev->_next = del->_next;

delete tmp;

}

}

};

void Test1()

{

List L1;

L1.PushFront(5);

L1.PushFront(4);

L1.PushFront(3);

L1.PushFront(2);

L1.PushFront(1);

L1.PushBack(6);

LinkNode* ret = L1.Find(5);

L1.Insert(ret,0);

L1.Print();

}

int main()

{

Test1();

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: