C++实现双向链表
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++实现双向链表相关的知识,希望对你有一定的参考价值。
双向链表
#include<iostream> using namespace std; typedef int DataType; struct Node { Node(const DataType&d) :_data(d) , _next(NULL) , _prev(NULL) {} Node*_next; Node*_prev; DataType _data; }; class DList { friend ostream&operator<<(ostream&os, DList& d); public: DList() :_head(NULL) , _tail(NULL) {} ~DList() { Node*cur=_head; while (cur) { Node*del = cur; cur = cur->_next; delete del; } } public: void PushBack(const DataType&d);//尾插 void PopBack();//尾删 void PushFront(const DataType&d);//头插 void PopFront();//头删2 private: Node*_head; Node*_tail; }; ostream&operator<<(ostream&os, DList& d) { Node* cur = d._head; while (cur) { cout << cur->_data << "<=>"; cur = cur->_next; } cout << "over" << endl; return os; } void DList::PushBack(const DataType&d)//尾插 { Node*newNode = new Node(d); if (_head == NULL) { _head = newNode; _tail = newNode; } else { _tail->_next = newNode; newNode->_prev = _tail; _tail = newNode; } } void DList::PopBack()//尾删 { if (_head == NULL)//没节点 { return; } if (_head == _tail)//一个节点 { delete _tail; _head = NULL; _tail = NULL; return; } //多节点 _tail = _tail->_prev; delete _tail->_next; _tail->_next = NULL; } void DList::PushFront(const DataType&d)//头插 { Node*newNode = new Node(d); if (_head == NULL) { _head = newNode; _tail = newNode; } else { newNode->_next = _head; _head->_prev = newNode; _head = newNode; } } void DList::PopFront()//头删 { if (_head == NULL) { return; } if (_head == _tail) { delete _tail; _tail = NULL; _head = NULL; return; } Node*del = _head; _head = _head->_next; _head->_prev = NULL; delete del; } Node*DList::Find(const DataType&d)//查找 { Node*cur = _head; while (cur) { if (cur->_data == d) { return cur; } cur = cur->_next; } return NULL; } void DList:: Insert(Node* pos, const DataType&d)//插入 { Node*newNode = new Node(d); if (pos == _tail) { _tail->_next = newNode; newNode->_prev = _tail; _tail = newNode; } else { newNode->_next = pos->_next; pos->_next->_prev = newNode; newNode->_prev = pos; pos->_next = newNode; } }
本文出自 “无以伦比的暖阳” 博客,请务必保留此出处http://10797127.blog.51cto.com/10787127/1752034
以上是关于C++实现双向链表的主要内容,如果未能解决你的问题,请参考以下文章