2014-01-13 32 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);