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

时间:2013-04-29 05:33:22

标签: 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;
}

4 个答案:

答案 0 :(得分: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;
}

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

答案 1 :(得分:1)

如果这是C ++,请不要使用malloc,如果这是C,请不要使用cout。你在编码很差的情况下混淆了两种语言。

每次打电话malloc时,你必须考虑的第一件事是“我什么时候可以自由?”在输入new之前你必须做的第一件事是“我什么时候删除?”。

要考虑的第二件事是“谁负责物品生活”:它是“拥有”整个清单的主要部分,还是相互欠缺的物品?或者它是别的东西(即列表本身是一个对象,而不仅仅是项目)

此时,请考虑两个类:一个node携带一个值,一个list主机节点,并提供购买和解除节点的方法,以及遍历节点。

答案 2 :(得分:0)

temp = (node*)malloc(sizeof(node)); 

您只分配一个节点,而您需要分配三个节点 因此,这个语句应该循环,以便可以为每个节点分配内存

答案 3 :(得分:0)

将其作为---&gt;

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;
      }
}

现在列表已填满&amp; head指向第一个节点,因此你可以访问它。