雙鏈表插入 刪除詳解


節點結構:

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 ;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章