#pragma once
#include <iostream>
using namespace std;
typedef int DataType;
struct SlistNode
{
SlistNode(const DataType& x)
:_data(x)
, _next(NULL)
{}
DataType _data;
SlistNode* _next;
};
class Slist
{
public:
Slist()
:_head(NULL)
, _tail(NULL)
{}
~Slist()
{
Clear();
}
Slist(const Slist& s)
:_head(NULL)
, _tail(NULL)
{
SlistNode* begin = s._head;
while (begin)
{
PushBack(begin->_data);
begin = begin->_next;
}
}
void Swap(Slist &s)
{
swap(_head, s._head);
swap(_tail, s._tail);
}
Slist &operator=(const Slist &s)
{
if (this != &s)
{
this->Clear();
Slist tmp(s);
Swap(tmp);
}
return *this;
}
public:
void Print()
{
if (_head == NULL)
{
return;
}
SlistNode* begin = _head;
while (begin != _tail)
{
cout << begin->_data << "->";
begin = begin->_next;
}
cout << begin->_data << endl;
}
void PushBack(const DataType &x)
{
//1.没有结点的空链表
if (_head == NULL)
{
_head = new SlistNode(x);
_tail = _head;
_tail->_next = _head;
return;
}
_tail->_next = new SlistNode(x);
_tail = _tail->_next;
_tail->_next = _head;
}
void PopBack()
{
if (_head == NULL)
{
return;
}
if (_head == _tail)
{
delete _head;
_head = NULL;
_tail = NULL;
return;
}
SlistNode* begin = _head;
while (begin->_next != _tail)
{
begin = begin->_next;
}
begin->_next = _head;
delete _tail;
_tail = begin;
}
void PushFront(const DataType &x)
{
if (_head == NULL)
{
_head = new SlistNode(x);
_tail = _head;
_tail->_next = _head;
return;
}
_tail->_next = new SlistNode(x);
_tail->_next->_next = _head;
_head = _tail->_next;
}
void PopFront()
{
if (_head == NULL)
{
return;
}
if (_head == _tail)
{
delete _head;
_head = NULL;
_tail = NULL;
return;
}
_tail->_next = _head->_next;
delete _head;
_head = _tail->_next;
}
SlistNode* Find(const DataType& x)
{
SlistNode* begin = _head;
if (_head == NULL)
{
return NULL;
}
do
{
if (begin->_data == x)
{
return begin;
}
begin = begin->_next;
} while (begin != _head);
return NULL;
}
//插到n后
void Insert(SlistNode *pos,const DataType &x)
{
//空链表
if (_head == NULL)
{
_head = new SlistNode(x);
_tail = _head;
_tail->_next = _head;
}
//插入到尾结点之后
else if (_tail == pos)
{
_tail->_next = new SlistNode(x);
_tail = _tail->_next;
_tail->_next = _head;
}
//插入到链表中间
else
{
SlistNode* tmp = pos->_next;
pos->_next = new SlistNode(x);
pos->_next->_next = tmp;
}
}
void Remove(SlistNode* pos)
{
if (_head == NULL)
{
return;
}
else if (_head == pos)
{
PopFront();
}
else
{
SlistNode* begin = _head;
while (begin->_next != pos)
{
begin = begin->_next;
}
begin->_next = pos->_next;
if (pos == _tail)
{
_tail = begin;
}
delete pos;
}
}
void Reserve()
{
if (_head == NULL || _head == _tail)
{
return;
}
SlistNode* begin = _head->_next;
SlistNode* NewHead = _head;
SlistNode* NewTail = _head;
NewHead->_next = NULL;
while (begin != _head)
{
SlistNode* tmp = begin;
begin = begin->_next;
tmp->_next = NewHead;
NewHead = tmp;
}
_head = NewHead;
_tail = NewTail;
_tail->_next = _head;
}
void Clear()
{
while (_head)
{
PopBack();
}
}
private:
SlistNode* _head;
SlistNode* _tail;
};
SCList
最新推荐文章于 2021-05-19 03:32:29 发布