节点定义
template <class T>
class Node
{
public:
T val;
class Node* next;
class Node* prev;
Node(T val) :val(val), next(NULL), prev(NULL) { ; }
Node() : next(NULL), prev(NULL) { ; }
};
链表类实现
template <class T>
class DList
{
private:
Node<T>* head;
int num;
public:
DList::DList()
{
head = new Node<T>();
head->next = head;
head->prev = head;
num = 1;
}
// 链表打印
void ListPrint()
{
Node<T>* cur = head->next;
while (cur != head)
{
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
// 尾插
void ListPushBack(T val)
{
Node<T>* newnode = new Node<T>(val);
newnode->prev = head->prev;
head->prev->next = newnode;
head->prev = newnode;
newnode->next = head;
num++;
}
// 尾删
void ListPopBack()
{
if (head->next == head)
return;
Node<T>* tail = head->prev;
head->prev = tail->prev;
tail->prev->next = head;
delete tail;
num--;
ListPrint();
}
// 头插
void ListPushFront(T val)
{
Node<T>* newnode = new Node<T>(val);
Node<T>* nextnode = head->next;
newnode->next = nextnode;
nextnode->prev = newnode;
head->next = newnode;
newnode->prev = head;
num++;
}
//头删
void ListPopFront()
{
// 判空
if (head->next == head)
return;
Node<T>* cur = head->next;
Node<T>* back = cur->next;
back->prev = head;
head->next = back;
num--;
delete cur;
}
// 查找链表中值为 val的的节点并返回
Node<T>* ListFind(T val)
{
Node<T>* cur = head->next;
while (cur != head)
{
if (cur->val == val)
return cur;
cur = cur->next;
}
return NULL;
}
// 节点插入
void ListInsert(int pos, T val)
{
assert(pos <= num && pos > 0);
Node<T>* newnode = new Node<T>(val);
Node<T>* cur = head;
while (--pos)
{
cur = cur->next;
}
newnode->next = cur->next;
cur->next->prev = newnode;
cur->next = newnode;
newnode->prev = cur;
num++;
}
// 节点删除
void ListErase(int pos)
{
Node<T>* cur = head;
Node<T>* prev = NULL;
assert(pos < num&& pos > 0);
while (pos--)
{
prev = cur;
cur = cur->next;
}
prev->next = cur->next;
cur->next->prev = prev;
delete cur;
num--;
}
//返回链表的大小
int size()
{
return num - 1;
}
~DList()
{
Node<T>* cur = head->next;
Node<T>* prev = NULL;
while (cur != head)
{
prev = cur;
cur = cur->next;
delete prev;
}
delete head;
}
};