2つの線形リスト
a:1→3→6→10→NULL
b:3→7→NULL
の差集合
a-b = 1→6→10→NULL
の線形リストを返す関数を作って
mainで出力させたのですが、
10としか出力されず、リストが繋がっていませんでした。
再帰関数で返り値をtailに代入しているので、連結していると思ったのですが、どうして連結されていないのかわかりません。
ご教示願います。
尚、メモリ解放については今の段階では考慮していないので、ご了承ください。
C
1#include <stdio.h> 2#include <stdlib.h> 3 4struct node { 5 int elm; 6 struct node *next; 7}; 8 9struct node *new(int e, struct node *n) { 10 struct node *p; 11 p = malloc(sizeof(struct node)); 12 p->elm = e; 13 p->next = n; 14 return p; 15} 16 17struct node *diff(struct node *a, struct node *b) { 18 struct node *head = new(0, NULL), *tail = head; 19 if(a==NULL || b== NULL) { 20 return a; 21 } 22 if(a->elm < b->elm) { 23 tail->next = new(a->elm, NULL); 24 tail= tail->next; 25 return tail->next = diff(a->next, b); 26 } 27 else if(a->elm == b->elm) { 28 return tail->next = diff(a->next, b->next); 29 } 30 else { 31 return tail->next = diff(a, b->next); 32 } 33} 34 35int main(void) { 36 struct node *a = new(1, new(3, new(6, new(10, NULL)))); 37 struct node *b = new(3, new(7, NULL)); 38 struct node *c = diff(a,b); 39 while(c!=NULL) { 40 printf("%d\n",c->elm); 41 c = c->next; 42 } 43 return 0; 44} 45
回答2件
あなたの回答
tips
プレビュー