1

私はリンクされたリストの初心者です。最初に1つのノードリンクリストを作成し、そのデータを表示しようとしましたが、 while(temp1!=NULL)条件のために表示されませんでした。次に、ループでいくつかの入力を取得しようとしましたが、未処理の例外のエラーが発生しました。これが私のコードです:

struct node
{
int data;
node* next;
};

//Initializing a NULL pointer for head
    node *head=NULL;

//create a temporary node 
    node *temp; 

//allocate space for node 
    temp = (node*)malloc(sizeof(node));

//Initilaizing avariable of node type to store data
node info;
for (int i=0;i<3;i++){
cout<<"Enter Data\t";
cin>>info.data;

//Store data(First Field)
temp->data=info.data;

//Store the address of the head pointer(Second Field)
temp->next=head;

//Converting temp into head since we are adding data from front
    temp=head;
}
  //==============Traversing the Link List=====================//
//Declaring a temporary pointer
 node *temp1;

//Assigning the address of head to temp1
temp1=head;

//Loop to traverse the list
cout<<"the data"<<endl;
while(temp1!=NULL)
{
    cout<<"the data is"<<endl;
    cout<<temp1->data<<endl;
    temp1=temp1->next;
}
4

4 に答える 4

6

ここに問題があります

temp = (node*)malloc(sizeof(node)); 
//Initilaizing avariable of node type to store data
node info;
for (int i=0;i<3;i++)
{
    cout<<"Enter Data\t";
    cin>>info.data;
    //Store data(First Field)
    temp->data=info.data;
    //Store the address of the head pointer(Second Field)
    temp->next=head;
    //Converting temp into head since we are adding data from front
    temp=head;
}

3 つの項目のリストを作成しようとしているため、3 つのノードを割り当てる必要があります。ただし、上記のコードは 1 つのノードのみを割り当てます。malloc呼び出しをループ内に移動して、3 回呼び出されるようにする必要があります。

于 2013-04-29T05:36:33.403 に答える
1

これが C++ の場合は malloc を使用しないでください。これが C の場合は cout を使用しないでください。貧弱なコーディングで 2 つの言語を混同しています。

電話をかけるたびに最初に考えなければならないことmallocは、「いつ解放されるのか」ということです。入力する前に最初にしなければならないことnewは、「いつ削除しますか?」です。

2 番目に考えるべきことは、「アイテムの寿命の責任者」です。リスト全体を「所有」するのはメインですか、それともアイテムは互いに負っていますか? それとも何か他のものですか(つまり、リスト自体はアイテムではなくオブジェクトです)

この時点で、2 つのクラスについて考えてみましょう。node値を運ぶクラスと、listノードをホストし、ノードを購入および破棄するメソッドを提供するクラス、ノードをウォークスルーするクラスです。

于 2013-04-29T06:22:16.833 に答える
0

次のようにします--->

node *head=NULL;
node *temp,*ptr;
temp=ptr=NULL
for (int i=0;i<3;i++)
{
     temp = (node*)malloc(sizeof(node));
     cout<<"Enter Data\t";
     cin>>info.data;
     //Store data(First Field)
     temp->data=info.data;
     //Store the address of the head pointer(Second Field)

      //Converting temp into head since we are adding data from front
      if(head== NULL)
      {
        head=temp;
        temp->next=NULL;
        ptr=temp;
       }
      else
      {
          ptr->next=temp;
          temp->next=NULL;
          ptr=temp;
      }
}

これでリストがいっぱいになり、head が一番最初のノードを指しているので、そこにアクセスできます。

于 2013-04-29T05:46:06.643 に答える
0
temp = (node*)malloc(sizeof(node)); 

ノードを 1 つだけ割り当てていますが、3 つを割り当てる必要があるため、このステートメントをループして、すべてのノードにメモリを割り当てることができるようにする必要があります。

于 2013-04-29T05:40:51.713 に答える