双向链表类:class List

来源:互联网 发布:网络名誉权司法解释 编辑:程序博客网 时间:2024/05/23 23:24
//双向链表//内容:默认4个,增删6个,打印,逆置,查找#pragma once#include<iostream>#include<assert.h>using namespace std;typedef int DataType;struct ListNode{ListNode* _next;ListNode* _prev;DataType _data;ListNode(DataType x):_next(NULL),_prev(NULL),_data(x){}};class List{typedef ListNode Node;public:List():_head(NULL),_tail(NULL){}List(const List& l):_head(NULL),_tail(NULL){Copy(l);}~List(){Destory();}//List& operator=(const List& l)//传统//{//if(this != &l)//{//Destory();//Copy(l);//}//return *this;//}List& operator=(List l)//现代{swap(_head, l._head);swap(_tail, l._tail);return *this;}void Insert(Node* pos, DataType x){//1.头插 2.中间assert(pos);if(_head == pos){Node* tmp = new Node(x);tmp->_next = pos;pos->_prev = tmp;_head = tmp;}else{Node* tmp = new Node(x);Node* prev = pos->_prev;Node* next = pos;prev->_next = tmp;tmp->_next = next;next->_prev = tmp;tmp->_prev = prev;}}void Erase(Node* pos){//1.1个 2.头删 3.尾删 4.中间//分头删尾删因为next和prev指向两端时候为空,空没有_next和_prevassert(pos);Node* next = pos->_next;Node* prev = pos->_prev;if(_head == _tail){_head = _tail = NULL;}else if (next == NULL){_tail = prev;prev->_next = NULL;}else if (prev == NULL){_head = next;next->_prev = NULL;}else{prev->_next = next;next->_prev = prev;}delete pos;}void Destory(){Node* cur = _head;while(cur){Node* del = cur;cur = cur->_next;delete del;}_head = _tail = NULL;}void Copy(const List& l){Node* cur = l._head;while(cur){PushBack(cur->_data);cur = cur->_next;}//PushBack已经把_head和_tail处理了,此处不用管了}Node* Find(DataType x){Node* cur = _head;while(cur){if(cur->_data == x){return cur;}cur = cur->_next;}return NULL;}void Print(){Node* cur = _head;while(cur){cout<<cur->_data<<" ";cur = cur->_next;}cout<<endl;}void Reverse_data()//链表逆序(交换数据){Node* left = _head;Node* right = _tail;while(right->_next != left && left != right){swap(left->_data, right->_data);left = left->_next;right = right->_prev;}}void Reverse_point()//链表逆序(反转指针){Node* cur = _head;while(cur){swap(cur->_prev, cur->_next);cur = cur->_prev;}swap(_head, _tail);}void PushBack(DataType x){//Insert是前插,无法复用//1.空 2.非空if(_head == NULL){_head = _tail = new Node(x);}else{Node* tmp = new Node(x);_tail->_next = tmp;tmp->_prev = _tail;_tail = tmp;}}void PushFront(DataType x){//Insert判定不为空链才进去,所以要分类讨论//1.空 2.非空if(_head == NULL){_head = _tail = new Node(x);}else{Insert(_head, x);}}void PopBack(){Erase(_tail);}void PopFront(){Erase(_head);}private:Node* _head;Node* _tail;};

原创粉丝点击