簡體   English   中英

了解鏈表C中的遞歸函數

[英]Understanding recursive function in linked-list C

假設我編寫了一個模擬多米諾骨牌游戲的程序,因此我想通過以下方式定義結構:

typedef struct nodo { 
    int casella1;
    int casella2;
    struct nodo *next;
} Tessera;
typedef Tessera *Lista;

然后以隨意的順序輸入結束,當輸入的數字超出范圍0 <= x <= 6時,我想刪除不遵守多米諾規則的可能重復項。 數字casella2應該始終使用遞歸函數在->next->casella1以相同的數字->next->casella1 ,如下所示:

void legale(Lista *head) {

    Lista aux,aus = *head;

    if(aus->next == NULL) {
      return;
    }

    else if(aus->casella2 == aus->next->casella1)   {
      legale(&(aus->next));
    }
    else {
      aux = aus->next;
      aus->next = aus->next->next;  
      free(aux);
    }
}

但是例如序列“ 1 2,2 3,3 4,4,5,5,6,2,7”給出“ 1 2,2 3,3,4,4、5、6 2”,因此它不會刪除6 ,2應該。

我認為刪除指針的方式是正確的,那么函數為什么出錯?

代碼如下:

#include<stdio.h>
#include<stdlib.h>
typedef struct nodo { 
    int casella1;
    int casella2;
    struct nodo *next;
    }Tessera;
typedef Tessera *Lista;

void stampa(Lista *head) {

    Lista ausil = *head;

    while(ausil != NULL) {
    printf("%d\t%d\n",ausil->casella1,ausil->casella2);
    ausil = ausil->next;
    }
}

void legale(Lista *head) {

    Lista aux,aus = *head;

    if(aus->next == NULL) {
    return;
}

    else if(aus->casella2 == aus->next->casella1)   {
    legale(&(aus->next));
}
    else {
    aux = aus->next;
    aus->next = aus->next->next;    
    free(aux);
}


}

void write (Lista *head) {
    Lista corr,aux,aus;
    int x,y;
    scanf("%d%d",&x,&y);
    aus = *head;

    while((x >= 0 && x <= 6) && (y >= 0 && y <= 6)) {

    if(aus == NULL) {

    aus = malloc(sizeof(Tessera));
    aus->casella1 = x;  
    aus->casella2 = y;
    aus->next = NULL;
    *head = aus;
}
    else {
    aux = *head;

    corr = malloc(sizeof(Tessera));
    corr->casella1 = x;
    corr->casella2 = y;
    corr->next = aux;
    *head = corr;
}
    scanf("%d%d",&x,&y);
    }

}

int main() {
    Lista Lista1 = NULL;
    write(&Lista1);
    legale(&Lista1);
    stampa(&Lista1);
return 0;
}

刪除重復項后,您至少錯過了一個遞歸調用,

 else { aux = aus->next; aus->next = aus->next->next; free(aux); } 

如果您不進行遞歸,則在第一次刪除后停止。

同樣通過預防措施,在檢查aus->next == NULL您應該檢查aus == NULL以便在傳遞空列表時也不會中斷。


編輯

閱讀時,您正在向后構造鏈接列表。

您將每對插入頭部,因此最后您的序列將向后。 閱讀清單以確保確定后,將其打印出來始終是一個好主意;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM