我有這個遞回函式:
struct singly* SetMinusRec(struct singly* shead1, struct singly* shead2){
struct singly* s2end;
s2end = shead2;
if(shead1 == NULL){
return NULL;
}else{
while(s2end != NULL && shead1->id < s2end->id){
s2end = s2end->next;
}
struct singly* new = (struct singly*)malloc(sizeof(struct singly));
if(shead1->id == s2end->id){
/* How can i not add this to the list, but just move on to the next node? */
}
printf("-%d %d-\n", shead1->id, s2end->id);
new->id = shead1->id;
new->next = SetMinusRec(shead1->next, shead2);
return new;
}
}
基本上,shead2 按降序排序,shead1 按遞增排序,我想創建一個新串列,其中包含 shead2 中不存在的 shead1 元素。當他們有相同的ID時我應該怎么做?我怎樣才能移動到下一個節點?
非常感謝。
uj5u.com熱心網友回復:
這個記憶體分配
struct singly* new = (struct singly*)malloc(sizeof(struct singly));
如果 . 會產生記憶體泄漏shead1->id == s2end->id。
另一方面,如果由于等式而不會分配記憶體并且指標new將被設定為NULL然后這個陳述句
new->next = SetMinusRec(shead1->next, shead2);
將呼叫未定義的行為。
還有這個 if 陳述句
if(shead1->id == s2end->id){
這個測驗輸出
printf("-%d %d-\n", shead1->id, s2end->id);
如果在 while 回圈之后指標s2end等于 ,則再次可以呼叫未定義的行為NULL。
該函式可以通過以下方式宣告和定義
struct singly * SetMinusRec( const struct singly *shead1, const struct singly *shead2 )
{
struct singly *shead = NULL;
if ( shead1 != NULL )
{
const struct singly *current = shead2;
while ( current != NULL && shead1->id < current->id )
{
current = current->next;
}
if ( current == NULL || current->id < shead1->id )
{
shead = malloc( sizeof( struct singly ) );
shead->id = shead1->id;
shead->next = SetMinusRec( shead1->next, shead2 );
}
else
{
shead = SetMinusRec( shead1->next, shead2 );
}
}
return shead;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/520609.html
標籤:C递归链表单链表函数定义
下一篇:如何在OCaml中執行組合數函式
