在c/c ++中操作链接列表

Aay*_*lil 1 c c++ data-structures

我是链接列表的初学者.最初我创建了一个单节点链接列表并尝试显示其数据,但它没有被显示 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;
}
Run Code Online (Sandbox Code Playgroud)

joh*_*ohn 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;
}
Run Code Online (Sandbox Code Playgroud)

您正在尝试构建三个项目的列表,因此您必须分配三个节点.但上面的代码只分配一个节点.您需要将调用移动到malloc循环内部,以便调用它三次.