C++双向链表
#include<iostream>
using namespace std;
template<typename T> class Node
{
public:
T key;
Node *pre;
Node *next;
Node(T x)
{
key = x;
pre = nullptr;
next = nullptr;
}
};
template<typename NodeT,typename keyT> class List
{
public:
NodeT *head;
bool isEmpty()
{
if(head == nullptr)
return true;
else
return false;
}
NodeT* search(keyT x)
{
NodeT *temp = head;
while(temp!=nullptr && temp->key!=x)
{
temp = temp->next;
}
return temp;
}
void insert(NodeT *node)
{
node->next = head;
if(head!=nullptr)
{
head->pre = node;
}
head = node;
node->pre = nullptr;
}
void del(keyT x)
{
NodeT *temp = search(x);
if (temp == nullptr)
{
cout<<"List is empty!"<<endl;
}
else
{
if(temp->pre!=nullptr && temp->next!=nullptr)
{
temp->pre->next = temp->next;
temp->next->pre = temp->pre;
}
else if(temp->pre == nullptr && temp->next!=nullptr)
{
temp->next->pre = nullptr;
head = temp->next;
}
else if(temp->pre != nullptr && temp->next==nullptr)
temp->pre->next = nullptr;
}
}
void show()
{
NodeT *temp = head;
while(temp!=nullptr)
{
cout<<temp->key<<" ";
temp = temp->next;
}
cout<<endl;
}
List()
{
head = nullptr;
}
};
int main(void)
{
List<Node<int>,int> l1;
l1.del(1);
Node<int> node1(1);
Node<int> *p = &node1;
l1.insert(p);
Node<int> node2(2);
p = &node2;
l1.insert(p);
Node<int> node3(3);
p = &node3;
l1.insert(p);
Node<int> node4(4);
p = &node4;
l1.insert(p);
Node<int> node5(5);
p = &node5;
l1.insert(p);
Node<int> node6(6);
p = &node6;
l1.insert(p);
Node<int> node7(7);
p = &node7;
l1.insert(p);
Node<int> node8(8);
p = &node8;
l1.insert(p);
l1.show();
for (int i=0;i<5;i++)
l1.del(2*i);
l1.show();
return 0;
}