【C++】用类实现单向单链表的尾插PushBack(),尾删PopBack(),打印PrintSlist()。
2016-03-03 20:26
701 查看
建立源文件,命名为:Slist.cpp。
建立头文件,命名为:Slist.h。
#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++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性