ページ 11

リスト構造の任意の位置に要素を挿入するプログラム

Posted: 2016年4月26日(火) 14:21
by po_po
あるリストと値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;
}

Re: リスト構造の任意の位置に要素を挿入するプログラム

Posted: 2016年4月26日(火) 19:36
by みけCAT
まだ詳しい解析はしていないですが、2番目のコードの15行目

コード:

list = add;
は、どうせ捨てられる仮引数への代入であり、その後listが全く使われていないので、怪しいですね。

Re: リスト構造の任意の位置に要素を挿入するプログラム

Posted: 2016年4月26日(火) 21:55
by みけCAT
最初のプログラムでは、nが1でないとき、以下のようにリストの更新が行われます。
list-20160426-1.png
最初のプログラムの動作
list-20160426-1.png (15.56 KiB) 閲覧数: 2519 回
2番目のプログラムでは、nが1でないとき、以下のようにリストは全く更新されず、メモリリークが発生します。
list-20160426-2.png
2番目のプログラムの動作
list-20160426-2.png (15.17 KiB) 閲覧数: 2519 回
オフトピック
しかしインデントが汚いコードだなあ…