0

これはおそらく C++ プログラマーにとって些細なことですが、私はこれを理解しようとしている初心者です。私のメインでは、短いリストを手動で印刷すると (cout << head->value など) 動作しますが、印刷機能を使用するとセグメンテーション違反が発生します。デバッガーを使用しようとしていますが、unix/c++ が苦手で、これを理解しようとしてイライラしています。

#include <iostream>
using namespace std;

class ListNode
{
    public:
    int value;
    ListNode* next;
};

void insertAtHead(ListNode** head, int value)
{
    ListNode *newNode = new ListNode;
    newNode->value = value;
    if(head == NULL)
    {
        *head = newNode;
        newNode->next = NULL;
    }
    else
    {
        newNode->next = *head;
        *head = newNode;
    }
}

void printList(ListNode* head)
{
    while(head != NULL)
    {
        cout << head->value << "->";
        head = head->next;
    }
}
//inserts after the node with given value
void insertAfterNode(ListNode** head,ListNode** newNode, int value)
{
    ListNode* current = *head;
    while(current != NULL && (current->value != value)) 
    {
            //cout << "Im Here";
            current = current->next;
            cout << current->value;
    }
    (*newNode)->next = current->next;
    current->next = *newNode;
}

int main()
{
    ListNode *head;
    insertAtHead(&head, 5);
    insertAtHead(&head, 10);
    ListNode* newNode = new ListNode;
    newNode->value = 8;
    newNode->next = NULL;
    insertAfterNode(&head,&newNode, 5);
printList(head);
}
4

3 に答える 3

2

関数でこの変更を確認してください

void insertAtHead(ListNode** head, int value)
{
    ListNode *newNode = new ListNode;
    newNode->value = value;

    newNode->next = *head;
    *head = newNode;
}

void printList(const ListNode* head)
{
    while(head != NULL)
    {
        cout << head->value << "->";
        head = head->next;
    }
}

あなたは二重ポインタを渡しているので、比較はこのinsertAtHeadようになるはずです。

*headアクセスする前に nullかどうかのチェックを追加しました。null新しいノードを次のように追加する場合head

void insertAfterNode(ListNode** head,ListNode** newNode, int value)
{
    ListNode* current = *head;
    if (current  != NULL)
    {
       while(current != NULL && (current->value != value)) 
       {
            //cout << "Im Here";
            current = current->next;
            cout << current->value;
       }
       (*newNode)->next = current->next;
       current->next = *newNode;
    }
    else
    {
      *head = *newNode;
    }
}

headそして、使用前のメインの初期化

int main()
{
    ListNode *head = NULL;
    insertAtHead(&head, 5);
    printList(head); // <== note: by-value, not by address or reference.
于 2013-04-24T04:46:45.087 に答える
0

アクセスしようとしている次の値が次のように null でないかどうかを確認する必要があります。

  void printList(ListNode* head)
    {
        if (head != NULL)
        {
            while(head->next != NULL)
            {
                cout << head->value << "->";
                head = head->next;
            }
        }
    }
于 2013-04-24T04:30:46.557 に答える