節點結構:
struct both_node
{
int key;
struct both_node *prev;
struct both_node *next;
both_node(int k)
:key(k),prev(NULL),next(NULL)
{}
};
不帶頭節點的雙鏈表實現插入 刪除,
雙鏈表
//插入
void insert_both(both_node *&head,int key)
{
if(head==NULL)
{
head= new both_node(key);
} else
{
both_node *tmp= new both_node(key);
if(head->next==NULL)//當插入時鏈表中只有一個節點的時候
{
head->next=tmp;
tmp->prev=head;
} else //鏈表中已經至少有兩個節點
{
tmp->next=head->next;
head->next->prev=tmp;
head->next=tmp;
tmp->prev=head;
}
}
}
//刪除
bool remove_both(both_node *&head,int key)
{
if(head==NULL)
return false ;
if(head->key==key)//如果是頭節點
{
if(head->next==NULL)//如果只有一個節點
{
delete head;
head=NULL;
} else//鏈表後面還有節點
{
both_node *tmp=head;
head=head->next;
head->prev=NULL;
delete tmp;
tmp=NULL;
}
return true ;
}
both_node *cur=head->next;
while(cur !=NULL && cur->key !=key)
cur=cur->next;
if(cur==NULL)//沒有找到
return false ;
if(cur->next !=NULL)//刪除的不是尾節點
{
cur->prev->next=cur->next;
cur->next->prev=cur->prev;
} else //刪除的是尾節點
{
cur->prev->next=NULL;
}
delete cur;
cur=NULL;
return true ;
}