2017-04-25 85 views
0
void removeNode(string sk2) { 
    nodelist *nodePtr, *previousNode; // keeps the list in memory 

    if (head->SKU == sk2) { 
    nodePtr = head->next; 
    delete head; 
    head = nodePtr; 
    } else { 
    nodePtr = head; 

    previousNode = NULL; 

    while (nodePtr != NULL && nodePtr->SKU != sk2) { 
     previousNode = nodePtr; 
     nodePtr = nodePtr->next; 
    } 
    previousNode->next = nodePtr->next; 
    delete nodePtr; 
    } 
} 

對不起,如果它的格式不正確,那麼這個網站和C++一般都是新的。我似乎無法理解這個鏈表如何執行刪除功能。有人可以解釋這段代碼嗎?

+0

這是一個成員功能?它看起來像'head'是一個成員變量,否則我不知道它來自哪裏。 – rwols

回答

0

在此代碼中,它將刪除鏈接列表的節點,其值爲從調用函數傳遞的sk2

我已經把它的意見,請參閱如果事情是不明確的,你可以問我:)

void removeNode(string sk2){ // function having string as a argument 

    nodelist *nodePtr, *previousNode; //keeps the list in memory Variable of type nodelist 


// here it is checking with the head of the link list whether that matches with the argument, as all linked list start with the Head 

    if (head->SKU == sk2){ 
     nodePtr = head->next; 
     delete head; // if so then delete that node 
     head = nodePtr; // and reassign the head to new node 
    } 

// if head parameter is not matching 
    else 
    { 
     nodePtr = head; 

     previousNode = NULL; 

    // travel up-to the node which has a data as a string passed as argument 
     while (nodePtr != NULL && nodePtr->SKU != sk2) 
     { 

     previousNode = nodePtr; 
     nodePtr = nodePtr->next; 
     } 
     previousNode->next = nodePtr->next; 
     delete nodePtr; // if found then delete that node 
    } 
} 
+0

謝謝!正是我正在尋找的! –

0

你似乎要刪除其中有sk2作爲SKU成員的節點。

第一個if只是檢查head節點是否是該節點,如果是,則刪除它。

如果沒有,那麼else塊試圖找到它。然後nodePtr是當前要檢查的節點,並且循環條件是:「只要我有一個節點要檢查並且它不是正確的」。 所以循環每次只獲取->next元素。此外,該循環始終保持前一個節點,因爲必須相應地設置->next字段。

如果循環完成以下兩種情況之一會發生:

  1. nodePtr包含正確的節點,它會被delted並以有效的方式
  2. nodePtrNULL恢復了聯繫。然後會發生未定義的行爲。
相關問題