帶鏈表的C無限循環

[英]C infinite loop with linked list

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

{
int data;

}element;

typedef element *elementptr;

void traverse(elementptr);

int main()
{
elementptr first = NULL,
last = NULL;

int input,num;

printf("Please enter first integer data: \n");
scanf("%d",&input);

//Create a linked list with user initialized data

first = (elementptr)malloc(sizeof(element));
last = first;
last -> data = input;
last -> next = NULL;

scanf("%d",&num);
traverse(first);

return 0;
}

{

while(i<num)
{
i++;

(*l) -> next = (elementptr)malloc(sizeof(element));
*l = (*l) ->next;
(*l) -> next = NULL;

}

}

void traverse(elementptr f)
{
elementptr current;
int count = 0;

current = f;
while (current != NULL)

{
count++;
printf("The data is %d \n", current->data);

}

printf("The linked list has %d elements \n",count);

}
``````

``````while (current != NULL)
{
count++;
printf("The data is %d \n", current->data);
}
``````

``````current = current->next
``````

`current = current -> next;` 您在while循環中缺少此語句。 盡管我建議：

``````#include<stdio.h>
#include<stdlib.h>
{
int number;
};
void create(node *p);
void print(node *p);
int main()
{
printf("---Start of the list ---\n");
printf("enter -1 to exit\n");
}
void create(node *list)
{
printf("enter the data");
scanf(" %d",&list->number);
if(list->number == -1)//Enter -1 to exit untill then keep on taking values
{
list->next=NULL;
}
else
{
list->next = (node*)malloc(sizeof(node));
create(list->next);
}
}

void print(node *list)
{
if(list->next != NULL)
{
printf("%d-->",list->number);
if((list->next->next == NULL) && (list->next->number!=-1))
printf("%d -->End of the List",list->next->number);
print(list->next);
}
}
``````

`traverse`功能中， `current`節點未指向下一個節點。 所以while條件`while (current != NULL)`將不成立，因此while循環無限運行。

``````void traverse(elementptr f)
{
elementptr current;
int count = 0;

current = f;
while (current != NULL)
{
count++;
printf("The data is %d \n", current->data);
// Fix
current = current->next;  // Point to next node in link list
}
}
``````