您的位置:首页 > 编程语言 > C语言/C++

【C++】用类实现单向单链表的尾插PushBack(),尾删PopBack(),打印PrintSlist()。

2016-03-03 20:26 701 查看
建立源文件,命名为: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__
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 单向 用类实现