用C++实现双向链表
来源:互联网 发布:国产电视知乎 编辑:程序博客网 时间:2024/06/03 23:43
#include<iostream>#include<assert.h>using namespace std;typedef int DataType; struct ListNode{ ListNode* _next; ListNode* _prev; DataType _data; ListNode(DataType x) :_data(x) , _next(NULL) , _prev(NULL) {}};class List{ typedef ListNode Node;public: List() :_head(NULL) , _tail(NULL) {} List(const List& l)//拷贝构造 :_head(NULL) , _tail(NULL) { if (l._head == NULL) { _head = _tail = NULL; } else { Node* head = l._head; while (head) { PushBack(head->_data); head = head->_next; } } }void Destroy(){ Node*cur = _head; while (cur) { Node* del = cur; cur = cur->_next; delete del; } _head = _tail = NULL;}List& operator=(const List& l){ if(this != &l) { Destroy(); Node*head = l._head; while (head) { PushBack(head->_data); head = head->_next; } } return *this;}~List() { Destroy();}void PushBack(DataType x){ if(_head == NULL) { _head = _tail = new Node(x); return; } else { Node* tmp =new Node(x); _tail->_next = tmp; tmp->_prev = _tail; _tail = _tail->_next; //_tail = tmp; }}void PopBack(){ assert(_head); if(_head == _tail) { delete _head; _head = _tail =NULL; } else { Node* prev =_tail->_prev; prev->_next = NULL; delete _tail; _tail = prev; }}void PushFront(DataType x){ if(_head = NULL) { _head = _tail = new Node(x); return; } else { Node* tmp =new Node(x); _head->_prev = tmp; tmp->_next =_head; _head = _head->_prev; }}void PopFront() { assert(_head); if(_head = _tail) { delete _head; _head = _tail =NULL; } else { Node* head = _head->_next; delete _head; _head = head; }}// 在pos的前面插入一个 void Insert(Node* pos, DataType x){ assert(pos); if(pos == _head) { PushFront(x); } else { Node*prev = pos->_prev; Node*tmp = new Node(x); prev->_next = tmp; tmp->_prev = prev; tmp->_next = pos; pos->_prev = tmp; }}void Erase(Node* pos) { assert(pos); if(pos == _head) { PopFront(); } else if(pos == _tail) { PopBack(); } else { Node* prev = pos->_prev; Node* next = pos->_next; prev->_next = next; next->_prev = prev; delete pos; }}Node* Find(DataType x){ Node* cur = _head; while(cur) if(cur->_data = x) { return cur; } cur = cur->_next;}void Reverse() {//双向链表的逆转 Node* begin = _head; Node* end = _tail; while (begin != end&&begin->_prev != end) { swap(begin->_data,end->_data); }}private: Node* _head; Node* _tail; };
阅读全文
0 0
- C/C++/JAVA 双向链表实现
- C语言实现双向链表删除、插入、双向输出
- 用双向链表实现Object-c 数组结构
- 双向链表的实现 c
- 双向链表代码实现-C语言
- 双向链表C语言实现
- C语言实现双向链表[上]
- C语言实现双向链表
- c语言双向链表的实现
- 双向链表的C实现
- 双向链表的C实现
- C语言实现双向循环链表
- c双向链表的实现
- C语言实现双向链表
- 双向链表的C语言实现
- c双向循环链表实现
- 双向链表的C实现
- 双向链表的C实现
- HDU 6047 Maximum Sequence
- CXF Weblogic 报错:Cannot create a secure XMLInputFactory
- <<python 核心编程>>第一章 正则表达式
- hdu6055 Regular polygon 2017多校联盟2 11题 -枚举
- 2017 Multi-University Training Contest
- 用C++实现双向链表
- poj 2104 K-th Number (主席树)
- 妙用Linux 的后台任务
- noip系列 2004提高组 合并果子
- BFC原理与清除浮动的关系
- 树状数组的基本运用
- 树状数组的基本+运用(HDU1166-敌兵布阵)
- linux-10 日志的管理
- 树状数组的进阶运用(Stars 数星星)