</pre><pre>
typedef struct Node{
int key;
Node *prev, *next;
}Node, *pNode;
typedef struct List{ //定义链表类
pNode firstNode; //List句柄(handle)
List();
void insert(pNode x);
}List;
List::List(){
firstNode = NULL;
}
void List::insert(pNode x){
if(firstNode == NULL)
firstNode = x;
else{ //寻找插入位置loc
pNode parent = firstNode;
pNode loc = parent;
while(loc != NULL && x->key > loc->key){
parent = loc;
loc = loc->next;
}
if(loc == firstNode){ //若loc为头节点
pNode temp = firstNode;
firstNode = x;
x->next = temp;
temp->prev = x;
}
else if(loc == NULL){ //若loc为尾节点
parent->next = x;
x->prev = parent;
}
else{ //若loc为中间节点
x->next = parent->next;
parent->next = x;
x->next->prev = x;
x->prev = parent;
}
}
}
测试:
void test(){
List lis;
Node x = {4,NULL,NULL};
Node x1 = {9,NULL,NULL};
Node x2 = {2,NULL,NULL};
Node x3 = {5,NULL,NULL};
lis.insert(&x);
lis.insert(&x1);
lis.insert(&x2);
lis.insert(&x3);
pNode temp = lis.firstNode;
while(temp != NULL){
cout<<temp->key<<" ";
temp = temp->next;
}
cout<<endl;
}
int main() {
test(); //输出:2 4 5 9
return 0;
}
设定firstNode不为NULL,而是minus infinity,则在调用handel入口时,必须为firstNode分配内存!
新的构造函数List():
List::List(){
firstNode = (pNode)malloc(sizeof(Node)); //重要!!在函数外调用firstNode必须要在Construction函数中分配内存!!!!
firstNode->key = -1;
firstNode->next = NULL;
}
新的插入函数:
void List::insert(pNode x){
pNode it = firstNode;
pNode par = firstNode;
while (it != NULL && it->key < x->key) {
par = it;
it = it->next;
}
x->next = par->next;
par->next = x;
x->prev = par;
if(x->next != NULL)
x->next->prev = x;
}
测试:
void test(){
List lis;
pNode temp = lis.firstNode; //要求lis.firstNode必须已分配内存,在List()用malloc函数
Node x = {4,NULL,NULL};
Node x1 = {9,NULL,NULL};
Node x2 = {2,NULL,NULL};
Node x3 = {5,NULL,NULL};
lis.insert(&x);
lis.insert(&x1);
lis.insert(&x2);
lis.insert(&x3);
while(temp != NULL){
cout<<temp->key<<" ";
temp = temp->next;
}
cout<<endl;
}
int main() {
test(); //输出:-1 2 4 5 9
return 0;
}