typedef int DataType;
class SListNode
{
private:
DataType _data;
SListNode* next;
friend class SList;
};
class SList
{
private:
SListNode* _head;
SListNode* _tail;
public:
SList()
:_head(NULL)
, _tail(NULL)
{}
//SList(DataType x)
// :_head(new SListNode)
// , _tail(_head)
//{
// _head->_data = x;
// _head->next = NULL;
//}
//*******构造带参********简便*******
SList(DataType x)
{
PushBack(x);
}
//**********************
SList(SList& s)
:_head(NULL)
{
SListNode* tmp = s._head;
while (tmp)
{
PushBack(tmp->_data);
tmp = tmp->next;
}
}
//***********传统***************
//SList& operator=(SList& s)
//{
// if (_head != s._head)
// {
// Clear();
// SListNode* cur = s._head;
// while (cur)
// {
// PushBack(cur->_data);
// cur = cur->next;
// }
// }
// return *this;
//}
//***********现代***************
SList& operator=(SList s)
{
if (_head != s._head)
{
swap(_head, s._head);
swap(_tail, s._tail);
}
return *this;
}
~SList()
{
Clear();
}
public:
void PushBack(DataType x)
{
SListNode* tmp = new SListNode;
tmp->_data = x;
tmp->next = NULL;
if (_head == NULL)
{
_head = tmp;
_tail = _head;
}
else
{
_tail->next = tmp;
_tail = _tail->next;
}
}
void PopBack()
{
if (_head != NULL)
{
SListNode* tmp = _head;
while (tmp->next != _tail)
{
tmp = tmp->next;
}
delete _tail;
_tail = tmp;
_tail->next = NULL;
}
}
void Clear()
{
SListNode* tmp = _head;
SListNode* del = _head;
while (tmp)
{
del = tmp;
tmp = tmp->next;
delete del;
del = NULL;
}
_head = NULL;
}
void PrintSList()
{
SListNode*tmp = _head;
while (tmp)
{
cout << tmp->_data << "->";
tmp = tmp->next;
}
cout << "NULL" << endl;
}
};