2012-10-20 4 views
2

Мой класс выполняет симуляцию проблемы Иосифа Флавия, реализуя круглый односвязный список. Мой код компилируется, но когда он запускается, я получаю ошибку сегментации: 11 после того, как список был создан. До сих пор моя отладка привела меня к пониманию того, что ошибка возникает, когда программа входит в конечный цикл цикла основной функции. Я думаю, что это имеет какое-то отношение к тому, как я использую first-> next, но я не уверен. Спасибо, спасибо. Я кодирую в C++, если это не очевидно.ошибка сегментации 11 связанный список

#include <iostream> 
#include <string> 
using namespace std; 



/* 
* Node structure used by the linked list. 
*/ 
struct Node { 
    // The name stored in this node. 
    string name; 

    // A pointer to the next node in the list. 
    Node * next; 
}; 

/* 
* Build the linked list 
*/ 

class LinkedList { 
    private: 
     //pointer to the head of the list 
     Node *head; 

    public: 
     // constructor for LinkedList 
     LinkedList(){ 
      head = NULL; 
     } 

     /* 
     * Add the given value to the list, making it the head. 
     */ 
     void insert(string name){ 


      // Remember where old head was 
      Node *oldHead = head; 

      // allocate a new node in memory 
      head = new Node; 

      // set new node's fields 
      head->name = name; 
      head->next = oldHead; 
     } 

     /* 
     * Remove the item on the top of the stack, returning nothing. 
     */ 
     void remove() { 
      // Remember what the new head will be 
      Node* newSecond = head->next->next; 

      // Deallocate the head from memory 
      delete head->next; 
      // Set the head to the new head 
      head->next = newSecond; 
     } 
     /* 
     * Shifts the head forward one node. 
     */ 
     void cycle(){ 

      head = head->next; 
     } 

     Node* getHead(){ 
      return head; 
     } 

     // This is the opposite of a constructor - a destructor! You (almost) 
     // never need these in Java, but in C++ they are essential because 
     // you have to clean up memory by yourself. In particular, we need to 
     // empty out the stack. 
     ~LinkedList() { 
      // While there's a head node still left, remove the head node. 
      while (head != NULL) { 
       remove(); 
      } 
     } 
}; 



int main(){ 
    //create the circular linked list 
    LinkedList circle; 

    int people; 
    cin >> people; 
    string soldier; 
    Node* first = circle.getHead(); 

    //Insert all the names 
    for(int i = 0; i < people; i++){ 
     cin >> soldier; 
     circle.insert(soldier); 
    } 

    //begin the killing 
    while(first->next != NULL){ 
     circle.cycle(); 
     cout << " killed " << endl; 
     Node* temp = first->next->next; 
     circle.remove(); 
     first->next = temp; 
    } 
} 
+0

'getHead' возвращает null, где вы его вызываете. –

ответ

0

Несколько проблем в этом коде. Во-первых это:

Node* newSecond = head->next->next; 

Если head->next является NULL, то вы получите указатель NULL разыменования. Это приводит к сбою.

Однако реальная причина этой конкретной аварии является то, что:

while(first->next != NULL) 

является NULL указатель разыменования. В начале main() у вас есть:

Node* first = circle.getHead(); 

circle пусто в этой точке, так first присваивается NULL. И он остается NULL до такой степени, что вы разыгрываете его в своем заявлении while. Таким образом, вы получаете сбой.

+0

, так как мне обойти эти проблемы? Я действительно новичок в C++ и все отсрочки. EDIT: nvr mind, я понял это. Спасибо, парни – midma101

Смежные вопросы