This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center
                            
                        
                    
                
                                6年前关闭。
            
                    
所以,伙计们,我试图在C中实现一个链表算法,下面是代码:

#include <stdio.h>
#include <stdlib.h>

typedef struct lista{
int info;
struct lista *next;
} *aplinked, strulinked;

aplinked insereNoFim(aplinked inicio, aplinked novo)
{
aplinked temp;
if (inicio == NULL)
    inicio = novo;
else{
    temp = inicio;
    while (temp->next != NULL)
        temp=temp->next;
    temp->next = novo;
}
return inicio;

}

aplinked lenovo()
{
aplinked x;
x = (aplinked) malloc (sizeof(strulinked));
scanf ("%d", &x->info);
return x;
}

void exibe(aplinked inicio){
aplinked temp = inicio;
if (temp == NULL)
printf ("Não existe dados");
else
while (temp!=NULL){
printf ("\n info: %d \n", temp->info);
temp = temp->next;
}
}


aplinked remover(aplinked inicio, int x)
{
aplinked ant = NULL;
aplinked temp = inicio;
//procura o elemento na lista, guardando o anterior.
while (temp!=NULL && temp->info != x){
        ant = temp;
        temp = temp->next;
}
//verifica se achou
if (temp == NULL)
    return inicio; //no caso de não achar
if (ant == NULL)
    inicio = temp->next; //retirar o 1o elemento
else
    ant->next = temp->next;
free (temp);
return inicio;
}



int pesquisa (aplinked inicio, int x){
aplinked temp = inicio;
while (temp!=NULL){
    if (temp->info == x)
        return 1;
    temp = temp->next;
    }
return 0;
}

int main ()
{
int cont = 1;
aplinked inicio = NULL;
while (cont){
inicio = insereNoFim(inicio, lenovo());
scanf ("%d", &cont);
}
exibe(inicio);
printf ("Digite numero a ser pesquisado: \n");
scanf ("%d", &cont);
if (pesquisa (inicio, cont))
    printf ("achou o elemento buscado \n");
else
    printf ("não achou");

printf ("Digite elemento a ser removido: \n");
scanf ("%d", &cont);
inicio = remover (inicio, cont);
exibe (inicio);
}


是的,代码不是英语,但是您可能对它的含义有所了解,因此,链表,删除/插入/搜索/打印功能在Linux上运行良好,但在Windows上运行却不正常! !

有任何想法吗?

最佳答案

我强烈建议您学习如何使用调试器。这是你的问题:

aplinked temp;
if (inicio == NULL)
    inicio = novo;
else{
    temp = inicio;
    while (temp->next != NULL)  //  you never set this to NULL
        temp=temp->next;


因为您从未将temp->next显式设置为NULL,所以其中可能包含任何内容。显然,在Linux上,它为NULL(很幸运),在Windows上,它只是垃圾。.junk != NULL因此,它尝试设置和取消引用它,然后崩溃。

您应该在lenovo()函数中填充结构的所有元素,而不仅仅是info

关于c - 语言C,算法在LINUX上运行良好,而不在Windows 7上运行? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15955920/

10-13 06:58