2013-04-29 139 views
1

我是初学者链接列表。最初,我创建了一个节点链接列表,并尝试显示其数据,但未显示条件的显示内容。 然后我试图采取一些在一个循环的投入,但现在我得到未处理的异常的错误,这里是我的代码:操作c/C++中的链接列表

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

“免费”在哪里?为什么malloc在C++? – 2013-04-29 06:12:28

回答

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,以便它被调用三次。

+0

@ John,谢谢:)输入问题已解决,但是我的代码仍然没有显示数据,从我所了解的while循环没有被执行,你能帮我吗? – 2013-04-29 05:40:32

+0

如果你看看你的代码,你有'head = NULL;'。你的代码中没有任何地方会改变head的值。所以当你进入while循环时它仍然是NULL。 'temp = head;'应该是'head = temp;'我会说。 – john 2013-04-29 05:42:30

+0

非常感谢John :) – 2013-04-29 05:46:23

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

你只分配一个节点,而你需要分配3 因此这种说法应该循环,使内存可以分配给每个节点

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

现在该列表已填充&头指向第一个节点,以便您可以访问它。

+0

@ akp,谢谢:) – 2013-04-29 07:14:02

+0

@ akp,你不觉得你的代码是从链接列表的后面插入数据吗? – 2013-04-29 08:12:41

+0

@AaymanKhalid是从后面插入数据...但你还没有指定应该在哪里插入节点!!!你可以修改,因为你的愿望...... >> – akp 2013-04-29 08:13:59

1

如果这是C++不要使用malloc,如果这是C,请不要使用cout。你用不好的编码混合了两种语言。

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

第二件要思考的问题是“谁负责物品的生命”:主要是“拥有”整个列表,还是彼此都欠缺?或者它是别的东西(即列表本身是一个对象,而不仅仅是项目)

在这一点上,想想两个类:一个node携带一个值,和一个list托管节点,并提供方法来购买和解雇一个节点,一个走过节点。