2014-01-13 2 views
1

기존 목록에 새 요소를 추가하는 프로그램을 구현할 때 문제가 있습니다. 여기있다 :목록에 새 요소를 추가하는 기능

#include <iostream> 
#include <stdio.h> 
#include <stdlib.h> 

using namespace std; 

struct person{ int v; 
      struct person *next; 

     }; 

void add(struct person *head, int n) 
    { struct person *nou; 
    nou=(person*)malloc(sizeof(struct person)); 
    nou->next=head; 
    head=nou; 
    nou->v=n; 
    } 

int main() 
{ 
struct person *head,*current,*nou; 

head=NULL; 

nou=(person*)malloc(sizeof(struct person)); 

nou->next=head; 
head=nou; 
nou->v=10; 


add(head,14); 

current=head; 
while(current!=NULL) 
{ cout<<current->v<<endl; 
    current=current->next; 

} 



return 0; 
} 

나는 그것을 실행할 때 값 10을 가진 요소 만있는 것으로 나타난다. 문제가 무엇입니까?

답변

1

값을 변경할 수 있도록 head 포인터에 대한 포인터를 전달해야합니다. 이 같은

void add(struct person **head, int n) 
{ 
    struct person *nou; 
    nou=(person*)malloc(sizeof(struct person)); 
    nou->next=*head; 
    *head=nou; 
    nou->v=n; 
} 

전화를 :

add(&head,14); 
관련 문제