建立源文件,命名为:Slist.cpp。
#include"Slist.h"
int main()
{
Test();
system("pause");
return 0;
}
建立头文件,命名为:Slist.h。
#ifndef __SLISH_H__
#define __SLIST_H__
#include<iostream>
using namespace std;
typedef int DataType;
class SlistNode
{
friend class Slist;
public:
SlistNode(DataType x)
:_next(NULL)
, _data(x)
{}
private:
DataType _data;
SlistNode* _next;
};
class Slist
{
public:
Slist()
:_head(NULL)
, _tail(NULL)
{}
Slist(const Slist& s)
:_head(NULL)
, _tail(NULL)
{
SlistNode* cur = s._head;
while (cur)
{
this->PushBack(cur->_data);
cur = cur->_next;
}
}
Slist& operator= (const Slist& s)
{
Slist tmp;
SlistNode* pcur = _head;
while (pcur)
{
SlistNode* del = pcur;
pcur = pcur->_next;
delete del;
del = NULL;
}
tmp = s;
SlistNode* cur = s._head;
while (cur)
{
this->PushBack(cur->_data);
cur = cur->_next;
}
}
~Slist()
{
SlistNode* cur = _head;
while (cur)
{
SlistNode* del = cur;
cur = cur->_next;
delete del;
del = NULL;
}
}
void PushBack(DataType x)
{
//0 1多
if (_head == NULL)
{
_head = new SlistNode(x);
_tail = _head;
}
else
{
/*_tail->_next = new SlistNode(x);
_tail = _tail->_next; */
SlistNode* cur = new SlistNode(x);
_tail->_next = cur;
_tail = cur;
}
}
void PopBack()
{
if (_head == _tail)
{
if (_head == NULL)
{
return;
}
else
{
delete _head;
_head = NULL;
_tail = NULL;
}
}
else
{
SlistNode* cur = _head;
while (cur)
{
SlistNode* _next = cur->_next;
if (_next == _tail)
{
delete _tail;
_tail = NULL;
_tail = cur;
_tail->_next = NULL;
}
cur = cur->_next;
}
}
}
void PrintSlist()
{
if (_head== NULL)
{
return;
}
else
{
SlistNode* cur = _head;
while (cur)
{
cout << cur->_data << " ";
cur = cur->_next;
}
cout << endl;
}
}
private:
SlistNode* _head;
SlistNode* _tail;
};
void Test()
{
Slist s;
s.PushBack(1);
s.PushBack(2);
s.PushBack(3);
s.PushBack(4);
s.PushBack(5);
s.PrintSlist();
s.PopBack();
s.PrintSlist();
}
#endif //__SLIST_H__
本文出自 “Han Jing's Blog” 博客,请务必保留此出处http://10740184.blog.51cto.com/10730184/1747325