SCList
来源:互联网 发布:java数学黑洞 编辑:程序博客网 时间:2024/05/17 21:54
#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;};
0 0