0

假设我编写了一个模拟多米诺骨牌游戏的程序,所以我想通过以下方式定义一个结构:

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

然后在以随意顺序进行一些输入后,当输入 0 <= x <= 6 范围之外的数字时结束,我想删除不遵守多米诺骨牌规则的可能重复项。使用递归函数,该数字casella2应始终以相同的数字作为后继,如下所示:->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 4, 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;
}
4

1 回答 1

1

删除重复项后,您至少错过了一次递归调用,

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

如果您不递归,则在第一次删除后停止。

同样为预防起见,在检查是否aus->next == NULL应该检查aus == NULL它是否不会中断,如果你将它传递给一个空列表。


编辑

当您阅读它时,您正在反向构建您的链表。

您将每一对插入头部,因此最后您的序列向后。阅读清单后打印出清单以确保一切正常,这总是一个好主意;)

于 2018-12-03T21:11:11.963 回答