2017-08-05 42 views
-3

我目前正在學習有關循環鏈表的問題,我遇到了一個循環鏈表模板的問題。它來源於ADT鏈接列表類型。虛擬頭節點圓形鏈表,刪除問題

我遇到的問題是刪除了節點,在某些情況下,當我刪除它們時,程序會崩潰。我知道當我創建一個列表來阻止這種情況發生時,我需要實現某種虛擬節點,但是我不知道是在代碼中執行此操作。

我看過其他文章,但我仍然失去了。

如果任何人都可以分享一些指導,如何實現這一點,我會如此 感激。

謝謝

插入:

template <class Type> 
void unorderedCircularLinkedList<Type>::insertFirst(const Type& newItem) 
{ 
    nodeType<Type> *newNode; 
    nodeType<Type> header; <--- implement here? 
    header.link = &header; <---- dereference the header? 
    newNode = new nodeType<Type>; //create the new node 
    newNode->info = newItem; //store the new item in the node 
    if (first == NULL) 
    { 
     first = newNode; 
     last = first; 
     last->link = first; 
    } 
    else 
    { 
     last->link = newNode;  //make last point to new node 
     newNode->link = first;  //make new node point to first 
     first = newNode;   //make first point to new node 
    } 
    count++;     //increment count 
} 

刪除:

template <class Type> 
void unorderedCircularLinkedList<Type>::deleteNode(const Type& deleteItem) 
{ 
    nodeType<Type> *current; //pointer to traverse the list 
    nodeType<Type> *trailCurrent; //pointer just before current 

    bool found; 

    if (first == NULL) //Case 1; the list is empty. 
     cout << "Cannot delete from an empty list." 
      << endl; 
    else 
    { 
     if (first->info == deleteItem) //Case 2 
     { 
      current = first; 
      count--; 
     if (first->link == first) //the list has only one node 
     { 
      first = NULL; 
      last = NULL; 
     } 
     else if (first->link == last) //the list has two nodes 
     { 
      first = first->link; 
      first->link = first; 
      last = first; 
     } 
     else 
     { 
      first = first->link; 
      last->link = first;  
     } 
     delete current; 
    } 
    else //search the list for the node with the given info 
    { 
     found = false; 
     trailCurrent = first; //set trailCurrent to point to the first node 
     current = first->link; //set current to point to the second node 
     /* set pointer to point to the last node*/ 
     while (current != NULL && !found) 
      if (current->info != deleteItem) 
      { 
       trailCurrent = current; 
       current = current->link; 
      } 
      else 
       found = true; 
     if (found) //Case 3; if found, delete the node 
     { 

      trailCurrent->link = current->link; 
      if (current == last) 
       first = first->link; 

      delete current; 

      count--; 

      //delete the node from the list 

     } 
     else 
      cout << "The item to be deleted is not in the list." << endl; 
     } 
    } 
} 
+0

學習如何使用調試器的時間。 – user0042

回答

0

你的花括號搞砸

if (first->info == deleteItem) //Case 2 
     { 
      current = first; 
      count--; 
     //missing '}' here 
     if (first->link == first) //the list has only one node 
     { 
      first = NULL; 
      last = NULL; 
     } 

並且我認爲當你添加上面的代碼時你會發現一個額外的代碼