typedef int DataType;
struct SListNode
{
SListNode* _next;
DataType _data;
SListNode(DataType x)
:_data(x)
,_next(NULL)
{}
};
typedef SListNode Node;
class SList
{
public:
SList(Node* head = NULL,Node* tail = NULL)
:_head(head)
,_tail(_head)
{}
void Swap(SList& s)
{
swap(_head,s._head);
swap(_tail,s._tail);
}
SList(const SList& s)
:_head(NULL)
,_tail(NULL)
{
if(s._head == NULL)
{
return ;
}
Node* tmp = s._head;
do
{
PushBack(tmp->_data);
tmp = tmp->_next;
} while (tmp!=s._head);
}
SList& operator=(const SList& s)
{
SList tmp(s);
Swap(tmp);
return *this;
}
~SList()
{
while(_head)
{
if(_head == _tail)
{
delete _head;
_head = NULL;
_tail = NULL;
}
else
{
Node* del = _head;
_head = _head->_next;
delete del;
_tail->_next = _head;
}
}
}
void PushBack(const DataType& x)//尾插
{//1.没有节点
//2.有多个节点
if (_head == NULL)
{
_head = new Node(x);
_tail = _head;
_tail->_next = _head;
}
else
{
Node *tmp = new Node(x);
_tail->_next = tmp;
tmp->_next = _head;
_tail = tmp;
}
}
void PopBack()
{
if(_head == NULL)
{
cout<<"SList is empty!"<<endl;
return;
}
else if(_head == _tail)
{
delete _head;
_head = NULL;
_tail = NULL;
return;
}
else
{
Node* cur = _head;
while(cur->_next!=_tail)
{
cur = cur->_next;
}
cur->_next = _head;
delete _tail;
_tail = cur;
}
}
void PushFront(DataType x)
{
if(_head == NULL)
{
_head = new Node(x);
_tail = _head;
_tail->_next = _head;
}
else
{
Node *tmp = _head;
_head = new Node(x);
_head->_next = tmp;
_tail->_next = _head;
}
}
void PopFront()
{
if(_head == NULL)
{
cout<<"SList is empty!"<<endl;
return;
}
else if(_head == _tail)
{
delete _head;
_head = NULL;
_tail = NULL;
return;
}
else
{
Node* del = _head;
_head = _head->_next;
delete del;
del = NULL;
_tail->_next = _head;
}
}
//寻找
Node* Find(DataType x)
{
if(_head == NULL)
{
cout << "SList is empty" << endl;
return NULL;
}
Node* cur = _head;
do
{
if(cur->_data == x)
{
return cur;
}
cur = cur->_next;
} while (cur!=_head);
return NULL;
}
// 插入一个节点在pos的前面
void Insert(Node* pos, DataType x)
{
assert(pos);
if(pos == _head)
{
PushFront(x);
}
else
{
Node* NewNode = new Node(x);
Node* cur = _head;
while(cur->_next!=pos)
{
cur = cur->_next;
}
cur->_next = NewNode;
NewNode->_next = pos;
}
}
void Erase(Node* pos)
{
assert(pos);
if(pos == _head)
{
PopFront();
}
else if(pos == _tail)
{
PopBack();
}
else
{
Node* cur = _head;
while(cur->_next!=pos)
{
cur = cur->_next;
}
cur->_next = pos->_next;
delete pos;
pos = NULL;
}
}
void Print()
{
if(_head == NULL)
{
cout<<"over"<<endl;
return;
}
Node* cur = _head;
do
{
cout<<cur->_data<<"->";
cur = cur->_next;
} while (cur!=_head);
cout<<"over"<<endl;
}
private:
Node* _head;
Node* _tail;
};
c++实现单链表
最新推荐文章于 2024-10-10 16:19:37 发布