sList.h
#pragma once
#include <iostream>
#include <assert.h>
using namespace std;
typedef int DataType;
struct SListNode
{
SListNode* _next;
DataType _data;
SListNode(DataType x)
:_data(x)
, _next(NULL)
{}
};
typedef SListNode Node;
class SList
{
public:
SList()
:_head(NULL)
, _tail(NULL)
{}
SList(const SList& s)
:_head(NULL), _tail(NULL)
{
if (s._head == NULL)
return;
else
{
Node* s_cur = s._head;
Node* cur = _head;
while (s_cur != s._tail)
{
cur = new Node(s_cur->_data);
cur = cur->_next;
s_cur = s_cur->_next;
}
cur = new Node(s_cur->_data);
//处理带环
if (s._tail->_next != NULL)
{
cur = _head;
s_cur = s._head;
while (s_cur != s._tail)
{
cur = cur->_next;
s_cur = s_cur->_next;
}
_tail->_next = cur;
}
//下面是复杂链表复制的方法
// //copy node
// Node* cur = s._head;
// while (cur != s._tail)
// {
// Node* copyNode = new Node(cur->_data);
// copyNode->_next = cur->_next;
// cur->_next = copyNode;
// }
// Node* copyNode = new Node(cur->_data);
// copyNode->_next = cur->_next;
// cur->_next = copyNode;
// //split
// cur = _head = s._head->_next;
// Node* s_cur = s._head;
// while (s_cur != s._tail)
// {
// s_cur->_next = s_cur->_next->_next;
// s_cur = s_cur->_next;
// cur->_next = cur->_next->_next;
// cur = cur->_next;
// }
// s_cur->_next = s_cur->_next->_next;
// s_cur = s_cur->_next;
// cur->_next = cur->_next->_next;
// cur = cur->_next;
}
}
SList& operator=(const SList& s)
{
SList newList(s);
Swap(newList);
return *this;
}
~SList()
{
if (_head != NULL)
{
while (_head != _tail)
{
Node* tmp = _head;
_head = _head->_next;
free(tmp);
}
free(_head);
}
}
void PushBack(DataType x)
{
if (_head == NULL)
{
_head = new Node(x);
_tail = _head;
}
else
{
_tail->_next = new Node(x);
_tail = _tail->_next;
}
}
void PopBack()
{
if (_head == NULL)
return;
if (_head == _tail)
{
delete _head;
_head = _tail = NULL;
}
else
{
Node* newTail = _head;
while (newTail->_next != _tail)
newTail = newTail->_next;
delete _tail;
_tail = newTail;
_tail->_next = NULL;
}
}
void PushFront(DataType x)
{
//Node* newHead = new Node(x);
//newHead->next = _head;
//_head = newHead;
//if (_tail == NULL)
// _tail = _head;
if (_head == NULL)
{
_head = new Node(x);
_tail = _head;
}
else
{
Node* newHead = new Node(x);
newHead->_next = _head;
_head = newHead;
}
}
void PopFront()
{
if (_head != NULL)
{
Node* oldHead = _head;
_head = _head->_next;
if (_head == NULL)
_tail = NULL;
}
}
// 插入一个节点在pos的前面
void Insert(Node* pos, DataType x)
{
assert(pos);
Node* newnode = new Node(pos->_data);
newnode->_next = pos->_next;
pos->_next = newnode;
pos->_data = x;
}
void Erase(Node* pos)
{
if (pos == _tail)
PopBack();
else
{
pos->_data = pos->_next->_data;
Node* tmp = pos->_next;
pos->_next = pos->_next->_next;
delete tmp;
}
}
void Print()
{
if (_head == NULL)
cout << "no data" << endl;
else
{
Node* cur = _head;
while (cur != _tail)
{
cout << cur->_data << ' ';
cur = cur->_next;
}
cout << cur->_data << endl;
}
}
private:
Node* _head;
Node* _tail;
};