あるリストと値nと挿入する要素を受け取ってリストのn番目にそれを挿入する関数を作ったのですが、これは正しく動くのですが
コード:
struct node *list_add(struct node *list ,long n,long data){
struct node* head = list;
long i;
node *add = (node *)malloc(sizeof(node));
add->data = data;
if(n == 1){
add->next = list;
list = add;
head = add;
}else{
for(i = 0; i < n-2; i++){
list = list->next;
}
add->next = list->next;
list->next = add;
}
return head;
}
こっちのプログラムはうまく動きません。どちらも同じことをしていると思うのになぜ結果が違うのでしょうか。教えて下さい。
コード:
struct node *list_add(struct node *list ,long n,long data){
struct node* head = list;
long i;
node *add = (node *)malloc(sizeof(node));
add->data = data;
if(n == 1){
add->next = list;
list = add;
head = add;
}else{
for(i = 0; i < n-1; i++){
list = list->next;
}
add->next = list;
list = add;
}
return head;
}