#include<iostream>
using namespace std;
typedef int DataType;
class LinkNode
{
public:
LinkNode(const DataType &x)
:_data(x)
, _prev(NULL)
, _next(NULL)
{}
friend class sList;
private:
DataType _data;
LinkNode *_prev;
LinkNode *_next;
};
class sList
{
public:
sList()
:_head(NULL)
, _tail(NULL)
{}
void PushBack(const DataType &x)
{
if (_head == NULL)
{
_head = new LinkNode(x);
_tail = _head;
return;
}
_tail->_next = new LinkNode(x);
_tail->_next->_prev = _tail;;
_tail = _tail->_next;
}
void PushFront(const DataType &x)
{
if (_head == NULL)
{
_head = new LinkNode(x);
_tail = _head;
return;
}
_head->_prev = new LinkNode(x);
_head->_prev->_next = _head;
_head = _head->_prev;
}
void PopBack()
{
if (_head == NULL)
{
return;
}
if (_head == _tail)
{
delete _head;
_head = NULL;
_tail = NULL;
return;
}
_tail->_prev->_next= NULL;
LinkNode *del = _tail;
_tail = _tail->_prev;
delete del;
}
void PopFront()
{
if (_head == NULL)
{
return;
}
if (_head == _tail)
{
delete _head;
_head = NULL;
_tail = NULL;
return;
}
LinkNode *del = _head;
_head = _head->_next;
delete del;
}
LinkNode *Find(const DataType &x)
{
LinkNode *begin = _head;
if (_head == NULL)
{
return NULL;
}
do
{
if (begin->_data == x)
{
return begin;
}
begin = begin->_next;
} while (begin);
return NULL;
}
//插入到n后
void Insert(LinkNode *n,const DataType &x)
{
//1.空链表
if (_head == NULL)
{
return;
}
//2.插到尾节点之后,更新尾节点
if (n == _tail)
{
_tail = new LinkNode(x);
n->_next = _tail;
_tail->_prev=n;
return;
}
//3.插到中间某个节点之后
LinkNode *tmp = new LinkNode(x);
tmp->_next = n->_next;
n->_next->_prev = tmp;
n->_next = tmp;
tmp->_prev = n;
}
void Erase(LinkNode *del)
{
//1.空表
if (_head == NULL)
{
return;
}
//2.只有一个结点
if (_head == _tail)
{
delete _head;
_head = NULL;
_tail = NULL;
return;
}
//3.删除头结点
if (_head == del)
{
_head = _head->_next;
delete del;
_head->_prev = NULL;
return;
}
//4.删除尾节点
if (del == _tail)
{
_tail = _tail->_prev;
_tail->_next = NULL;
delete del;
return;
}
//5.删除中间的某一结点
del->_prev->_next = del->_next;
del->_next->_prev = del->_prev;
delete del;
}
void Print()
{
if (_head == NULL)
{
return;
}
LinkNode *begin = _head;
cout << "SList->";
while (begin)
{
cout << begin->_data << "->";
begin = begin->_next;
}
cout << endl;;
}
private:
LinkNode *_head;
LinkNode *_tail;
};
int main()
{
sList op1;
op1.PushBack(1);
op1.PushBack(2);
op1.PushBack(3);
//op1.PushBack(4);
op1.Print();
/*op1.PopBack();
op1.PopBack();
op1.PopBack();
op1.PopBack();
op1.PopBack();*/
/*op1.PushFront(10);
op1.PushFront(20);
op1.PushFront(30);
op1.Print();
op1.PopFront();
op1.PopFront();
op1.PopFront();
op1.PopFront();
op1.Print();*/
LinkNode *ret = op1.Find(4);
if (ret != NULL)
{
op1.Insert(ret, 100);
}
/*if (ret != NULL)
{
op1.Erase(ret);
}*/
op1.Print();
system("pause");
return 0;
}
【C++】双向链表
最新推荐文章于 2024-06-15 09:00:00 发布