实现一个双向链表

来源:互联网 发布:文献查重软件 编辑:程序博客网 时间:2024/06/06 12:44

实现一个双向链表的增删查改代码如下:

#include<iostream>
#include<assert.h>
using namespace std;
typedef int DataType;
struct ListNode
{
ListNode* _next;
ListNode* _prev;
ListNode* _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)
{
Node* cur = l._head;
while (cur)
{
PushBack(cur->_data);
cur = cur->_next;
}


}
List& operator=(const List&l)
{
if (this != &l)
{
List tmp(l);
Swap(tmp);
}
return *this;
}
void Swap(List &l)
{
swap(_head, l._head);
swap(_tail, l._tail);
}
~List()
{
if (_head != NULL)
{
Node* del = _head;
_head = _head->_next; 
delete del;
}
}
void PushBack(DataType x)
{
if (_head == NULL)
{
_head = _tail = new Node(x);
}
else
{
Node*cur = new Node(x);
_tail->_data = cur;
cur->_prev = _tail;
_tail = cur;
}
}
void Print()
{
Node* cur = _head;
while (cur != NULL)
{
cout << cur-> _data << "->";
cur = cur->_next;
}
cout << "NULL" << endl;
}
void PopBack()
{
if (_head == NULL)
{
return;
}
else if (_head->_next == NULL)
{
Node* cur = _head;
delete cur;
_head = NULL;
_tail = NULL;
}
else
{
Node* cur = _tail;
cur->_prev->_next = NULL;
_tail = cur->_prev;
delete cur;
}
}
void PushFront(DataType x)
{
if (_head == NULL)
{
_head = _tail = new Node(x);
}
else
{
Node* tmp = _head;
_head = new Node(x);
_head->_prev = _head;
}
}
void PopFront()
{
if (_head == NULL)
{
return;
}
else if (_head->_next ==NULL)
{
Node* cur = _head;
delete cur;
_head = NULL;
_tail = NULL;
}
else
{
Node* cur = _head;
_head = _head->_next;
delete cur;
_head->_prev = NULL;
}
}
void Insert(Node* pos, DataType x)
{
assert(pos);
if (pos == _head)
{
PushFront(x);
}
else
{
Node* tmp = new Node(x);
Node* prev = pos->_prev;
Node* next = pos->_prev->_next;
prev->_next = tmp;
tmp->_next = next;
next->_prev = tmp;
tmp->_prev = prev;
}
}
void Erase(Node* pos)
{
assert(pos);
if (pos == _head)
{
PopFront();
}
else if (pos == _tail)
{
PopBack();
}
else
{
pos->_next->_prev = pos->_prev;
pos->_prev->_next = pos->_next;
delete pos;
}
}
Node* Find(DataType x)
{
Node* cur = _head;
while (cur)
{
if (cur->_data == x)
{
return cur;
}
cur = cur->_next;
}
return NULL;
}
void Reverse()
{
Node* prev = _head;
while (prev)
{
Node* next = prev->_next;
Node* tmp = prev->_prev ;
prev->_prev = prev->_next;
prev->_next = tmp;
prev = next;
}
Node* tmp = _head;
_head = _tail;
_tail = tmp;
}


private:
Node* _head;
Node* _tail;
};

原创粉丝点击