2012-04-17 166 views
1

這裏是我的代碼,用於刪除參數中傳遞值的所有節點。刪除鏈接列表中的節點

typedef struct nodetype 
{ 
    int data; 
    struct nodetype * next; 
} node; 

typedef node * list; 


void Linklist::deleteNode(list * head, int value) 
{ 

    list current = *head; 
    list previous = *head; 
    while(current != NULL) 
    { 
     if(current->data != value) 
     { 
       previous = current; 
       current = current->next; 
     } 

     else if (current->data == value) 
     { 
      previous->next = current->next; 
      delete current; 
      current = previous->next; 

     } 
    } 
} 

但在這裏,如果在鏈表的所有元素是說2,那麼就應該刪除鏈表的所有元素,並最終負責人也應該成爲NULL,這樣,如果我通過這個頭計算節點的數量在列表中應該說列表是空的和其他類似的操作。

根據我目前的實施情況,頭部在上述情況下不會變爲NULL。

請建議修改,以便如果鏈接列表中的所有節點具有在函數參數中傳遞的相同值,則頭應該變爲NULL。

+3

其工作文件,如果不做作業,請嘗試使用'的std :: list'容器類。如果這是作業,請在作業中添加「作業」標籤。 – 2012-04-17 20:16:08

回答

2

我修改我的代碼如下現在

void Linklist::deleteNode(list *head, int value) 
{ 

    list * current = head; 
    list * previous = head; 
    bool flag = false; 
    while(*current != NULL) 
    { 
     if((*current)->data != value) 
     { 
      *previous = *current; 
      *current = (*current)->next; 
     } 

     else if ((*current)->data == value) 
     { 
      flag = true; 
      (*previous)->next = (*current)->next; 
      delete *current; 
      *current = (*previous)->next; 

     } 
    } 
    if(!flag) 
     cout<<"Element not found in the linklist\n"; 
    cout<<"Count is "<<Linklist::count(*head)<<endl; 
}