0

int 値のリンク リストを作成しようとしています。リストに3つのint値を追加し、それらを印刷しますが、3つの値を印刷した後、プログラムは印刷関数に戻って4番目の値を印刷します。 3つの値なので、printメソッドでアクセス違反の読み取りエラーが発生しますcout << "index " << size-- << ", value: "<< tempNode->num << endl;

リストノードを超えていますが、どこが間違っているのかわかりません。

助けてください、2日間これを理解しようとしています.

以下のコード。

IntList::IntList()
{
    first = NULL;
    last = NULL;
    size = 0;
}


 IntList::Node::Node(const int& info, Node* next = NULL)
 {
    num = info;
    next = next;
 }


 IntList::~IntList()
 {
    Node* tempNode = first;
    while ( tempNode != NULL )
    //for(int i = 0; i < size; i++)
    {
        Node* nextNode = tempNode->next;
        delete tempNode;
        tempNode = nextNode;
    }

    first = last = NULL;
    size = 0;
  }


IntList::IntList(const IntList& wl)
{
     cout << "here word list copy conts " << endl;

     first = last = NULL;
     size = wl.size;
     if(wl.first != NULL){

        Node* tempNode = wl.first;
        for(int i = 0; i < wl.size; i++)
        {
              addLast(tempNode->num);
              tempNode = tempNode->next;
        }
     }
}


IntList& IntList::operator = (const IntList& wl)
{
    cout << "here word list =" << endl;
    if(this == &wl)
        return *this;

    Node* tempNode = first;
    while ( tempNode != NULL )
    {
        Node* nextNode = tempNode->next;
        delete tempNode;
        tempNode = nextNode;
    }

    first = NULL;
    last = NULL;

    if(wl.first != NULL)
    {
        for(int i = 0; i < wl.size; i++)
        {
           addLast(tempNode->num);
           tempNode = tempNode->next;
           size++;
    }
}

return *this;
}

 void IntList::addFirst(int& winfo)
{
    Node* firstNode = new Node(winfo);
    //Node firstNode(winfo);
    if(first == NULL) 
    {
        first = last = firstNode;
    }
    else 
    {
        firstNode->next = first;
        first = firstNode;  
    }
    //increment list size
    size++;
}

void IntList::print(ostream& out)
{
    Node* tempNode = first;
    while ( tempNode != NULL )
    {
        out << "\t";
        cout << "index " << size-- << ", value: "<< tempNode->num << endl;
        tempNode = tempNode->next;
    }
 }
4

1 に答える 1

2

コンストラクターのnextパラメーターはそのメンバーをNodeシャドウするため、パラメーターに代入します。 それらのいずれかの名前を変更します。nextnext = next

また、size印刷中は変更しないでください。

于 2012-05-18T16:23:52.980 に答える