顺序表和链表几乎是面试必考点,前面我们已经介绍过了模板顺序表(http://blog.csdn.net/ChaseRaod/article/details/70477564)
这篇文章给大家介绍介绍一下模板双向链表
用模板写链表主要还是为了实现代码的类型通用性,以下代码将实现链表的增、删、查、改、判空等操作。
#define _CRT_SECURE_NO_WARNINGS 1
#pragma once
#include<iostream>
#include<stdlib.h>
using namespace std;
template<class T>//关于节点的模板类
struct ListNode
{
ListNode(const T& x)//构造函数
:_data(x)
, _next(NULL)
, _prev(NULL){}
T _data;
ListNode<T>* _next;
ListNode<T>* _prev;
};
template <class T>
class List
{
typedef ListNode<T> Node;
public:
List()
:_head(NULL)
, _tail(NULL){}
List(const List<T>& l)//拷贝构造
:_head(NULL)
, _tail(NULL)
{
Node* cur = l._head;
while (cur)
{
PushBack(cur->_data);
cur = cur->_next;
}
}
~List()//析构函数
{
Node* cur = _head;
while (cur)
{
Node* next = cur->_next;
delete cur;
cur = next;
}
_head = _tail = NULL;
}
bool Empty()//判NULL
{
return _head == 0;
}
Node* Find(const T& x)//查找
{
if (_head == NULL)
{
return NULL;
}
int i = 0;
Node* cur = _head;
while (cur)
{
if (cur == x)
{
return cur;
}
cur = cur->_next;
}
return NULL;
}
size_t Size()//大小
{
Node* cur = _head;
int count = 0;
while (cur)
{
count++;
cur = cur->_next;
}
return count;
}
void PushBack(const T& x)//后插
{
if (_head == NULL)//链表为空
{
_head = _tail = new Node(x);
}
else
{
Node* tmp = new Node(x);//开辟一块新的空间
_tail->_next = tmp;
tmp->_prev = _tail;//双向链表
_tail = tmp;
}
}
void PopBack()//后删
{
if (_head == NULL)
{
return;
}
else if (_head == _tail)
{
delete _head;
_head = _tail = NULL;
}
else
{
Node* prev = _tail->_prev;
delete _tail;
_tail = prev;
_tail->_next = NULL;
}
}
void PushFront(const T& x)//前插
{
if (_head == NULL)
{
_head = _tail = new Node(x);
}
else
{
Node* tmp = new Node(x);
_head->_prev = tmp;
tmp->_next = _head;
_head = tmp;
}
}
void PopFront()//前删
{
if (_head == NULL)
{
return;
}
else if (_head == _tail)
{
delete _head;
_head = NULL;
}
else
{
Node* tmp = _head;
_head = _head->_next;
delete _tmp;
}
}
void Insert(Node* pos,const T& x)//指定位置插入
{
assert(pos);
Node* prev = pos->_prev;
Node* next = pos;
Node* cur = new Node(x);
if (prev)
{
prev->_next = cur;
cur->_next = prev;
}
cur->_next = next;
next->_prev = cur;
}
void Erase(Node* pos)//指定位置删除
{
assert(pos);
Node* prev = pos->_prev;
Node* next = pos->_next;
if (_head == NULL)
{
return;
}
if (_head == _tail)
{
delete _head;
_head = _tail = NULL;
}
else if (prev == NULL)
{
Node* cur = _head;
cur = cur->_next;
delete _head;
_head = cur;
}
else if (next == NULL)
{
Node* cur = _tail;
cur = cur->_prev;
delete _tail;
_tail = cur;
}
else
{
prev->_next = next;
next->_prev = prev;
delete pos;
}
}
void Print()//打印
{
Node* cur = _head;
while (cur)
{
cout << cur->_data<< " ";
cur = cur->_next;
}
}
List<int>& operator = (List<T> l)//赋值运算符重载
{
swap(l._head, _head);
swap(l._tail, _tail);
return *this;
}
private:
Node* _head;
Node* _tail;
};
//测试用例
void Funteat()
{
List<int> l1;
l1.PushBack(1);
l1.PushBack(2);
l1.PushBack(3);
l1.PushBack(4);
l1.Print();
}
int main()
{
Funteat();
system("pause\n");
return 0;
}
打印结果如下: