Cpp_链表
来源:互联网 发布:wiffi转网络接口 编辑:程序博客网 时间:2024/06/01 08:59
代码如下:
【List.h】
#pragma oncetypedef int DataType;#include <iostream>#include <assert.h>using namespace std;struct SlistNode{ SlistNode* _next; DataType _data; SlistNode(DataType x) :_data(x) , _next(NULL) {}};class Slist{ typedef SlistNode Node;public: Slist() //构造函数 : _head(NULL) , _tail(NULL) {} Slist(const Slist& s); Slist& operator=(const Slist& s); ~Slist() //析构函数 { Node* cur = _head; while (cur) { Node* next = cur->_next; delete cur; cur = next; } _head = _tail = NULL; } Node* BuyNode(DataType x) //创建新节点 { Node* node = (Node*)malloc(sizeof(Node)); node->_data = x; node->_next = NULL; return node; } void PushBack(DataType x) //后插 { if (_head == NULL) { _head = _tail = new Node(x); } else { _tail->_next = new Node(x); _tail = _tail->_next; } } void PopBack() //后删 { if (_head == NULL) { return; } else if (_head == _tail) { delete _head; _head = _tail = NULL; } else { Node* prev = _head; while (prev->_next != _tail) { prev = prev->_next; } delete _tail; _tail = prev; _tail->_next = NULL; } } void PushFront(DataType x) //前插 { if (_head == NULL) { _head = _tail = new Node(x); } else { Node* tmp = new Node(x); tmp->_next = _head; _head = tmp; } } void PopFront() //前删 { if (_head == NULL) { return; } else if (_head == _tail) { delete _head; _head = _tail = NULL; } else { Node* del = _head; _head = _head->_next; delete del; } } void Print() //打印 { Node* cur = _head; while (cur) { cout << cur->_data << " "; cur = cur->_next; } cout << endl; }private: Node* _head; Node* _tail;};void TestSlist(){ Slist s; s.PushBack(1); s.PushBack(2); s.PushBack(3); s.PushBack(4); s.PushBack(5); s.Print();}
【test.cpp】
#include "List.h"int main(){ TestSlist(); return 0;}
阅读全文
1 0
- Cpp_链表
- Cpp_引用
- Cpp_继承
- Cpp_多态
- Cpp_函数重载
- Cpp_函数缺省参数
- Cpp_内联函数
- Cpp_动态内存分配
- Cpp_类型转换
- Cpp_类和对象
- Cpp_构造函数
- Cpp_析构函数
- Cpp_静态成员
- Cpp_成员指针
- Cpp_操作符重载
- Cpp_异常处理
- Cpp_顺序表
- Cpp_继承&对象模型
- keil5通过jlink向stm32f103烧写程序 出错
- 通讯录 c++ list版
- 文章标题
- Go操作Mysql报错Can't create more than max_prepared_stmt_count statements
- 关于面向对象的一些理解(1)
- Cpp_链表
- 网页的性能优化的小知识
- TCP握手与挥手
- Xutils请求网络数据
- 通过符号左右移动数据easyui
- shell学习(一)
- 基于Docker的TensorFlow机器学习框架搭建和实例源码解读
- SPOJ DQUERY(树状数组离线处理 or 主席树 区间不同数个数)
- Ubuntu使用mysql添加数据异常解决办法