自己写的个有序的双向链表:
#include<iostream>
using namespace std;
template<class T>
class dNode
{
public:
dNode* pre;
dNode* next;
T content;
};
template<class T>
dNode<T>* insertNode(dNode<T> *&head ,const T &n)
{
dNode<T> *newNode = new dNode<T>;
newNode->content = n;
dNode<T> *move = head;
if(head == NULL)//////////////////链表为空
{
head = newNode;
head->pre = NULL;
head->next = NULL;
return head;
}
else
{
if(n<=head->content)//////////////表头插入
{
newNode->pre = 0;
newNode->next = head;
head->pre = newNode;
head = newNode;
return head;
}
else
{
while(n>move->content&&move->next!=NULL)
{
move=move->next;
}
if(n>move->content)///////插入链表末端
{
newNode->pre = move;
newNode->next = 0;
move->next = newNode;
}
else ////////////////表中间插入
{
newNode->pre = move ->pre;
newNode->next = move;
move->pre->next = newNode;
move->pre = newNode;
}
return newNode;
}
}
}
template<class T>
void displayLink(const dNode<T> *const head)
{
const dNode<T> *move = head ;
while(move!=0)
{
cout<<move->content<<endl;
move=move->next;
}
}
template<class T>
dNode<T>* searchNode(dNode<T> *&head ,const T &n)
{
dNode<T> *move = head ;
while(n>move->content&&move->next!=0)
{
move = move->next;
}
if(n==move->content)
{
return move;
}
else
{
return NULL;
}
}
template<class T>
void find(dNode<T> *&head ,const T &n)
{
dNode<T> *key = searchNode(head ,n);
if(key==0)
{
cout<<"无此记录"<<endl;
}
else
{
cout<<key->content<<endl;
}
}
template<class T>
dNode<T>* deleteNode(dNode<T> *&head ,const T &n)
{
dNode<T> *move = searchNode(head ,n);
if(move!=0)
{
if(move->pre == 0)/////////////////////删除表头
{
move->next->pre = 0;
head = head->next;
delete move;
move = 0;
return head;
}
else if(move->next== 0)/////////////删除链表尾部
{
move->pre->next = 0;
}
else/////////////////////////////删除中间元素
{
move->pre->next = move->next;
move->next->pre = move->pre;
}
move = move->pre;
return move;
}
else
{
return NULL;
}
}
int main()
{
dNode<int> *head = 0;
//dNode<int> *head=new dNode<int>;
int a = 6;
insertNode(head,a);
insertNode(head,4);
insertNode(head,5);
insertNode(head,7);
// cout<<k->pre->content<<endl;
displayLink(head);
dNode<int> *k = searchNode(head,1);
deleteNode(head ,7);
find(head,7);
displayLink(head);
// cout<<k->content<<endl;
return 1;
}