typedef struct numbers{
int number_inserted;
struct numbers *next;
}NUMBERS;
int main(){
NUMBERS * num=NULL
int i=0;
while(i<5){
num=add_number(num);
i++;
}
}
NUMBERS * add_number(NUMBERS *num){
if (num== NULL) {
num = (NUMBERS *) malloc(sizeof(NUMBERS));
num->number_inserted=0;
num->next = NULL;
}
int gets;
printf("Insira o numero");
scanf("%d",&gets);
num->number_inserted=gets;
num->next = ????????
return num;
}
如何为我的结构NUMBERS链接我的变量num-&gt;那么当再次调用它时我不会丢失之前插入的数字。
答案 0 :(得分:0)
对于根据C标准的初学者,没有参数的函数main应声明为
int main( void )
此外,您似乎在main中定义了函数add_number
(如果您没有省略main的右括号)。 C标准不允许在另一个函数内声明一个函数。
通常,如果声明单链接的单边列表,则列表中的节点将添加到其开头。
这是一个演示程序,显示如何将新节点添加到单链表的开头和结尾。
#include <stdio.h>
#include <stdlib.h>
typedef struct numbers
{
int number_inserted;
struct numbers *next;
} NUMBERS;
int add_number_front( NUMBERS **numbers, int x )
{
NUMBERS *tmp = malloc( sizeof( NUMBERS ) );
int success = tmp != NULL;
if ( success )
{
tmp->number_inserted = x;
tmp->next = *numbers;
*numbers = tmp;
}
return success;
}
int add_number_back( NUMBERS **numbers, int x )
{
NUMBERS *tmp = malloc( sizeof( NUMBERS ) );
int success = tmp != NULL;
if ( success )
{
tmp->number_inserted = x;
tmp->next = NULL;
while ( *numbers != NULL ) numbers = &( *numbers )->next;
*numbers = tmp;
}
return success;
}
void display_numbers( NUMBERS **numbers )
{
for ( NUMBERS *current = *numbers; current != NULL; current = current->next )
{
printf( "%d ", current->number_inserted );
}
}
int main(void)
{
NUMBERS *numbers = NULL;
for ( int i = 0; i < 5; i++ ) add_number_back( &numbers, i );
display_numbers( &numbers );
putchar( '\n' );
for ( int i = 0; i < 5; i++ ) add_number_front( &numbers, i );
display_numbers( &numbers );
putchar( '\n' );
return 0;
}
它的输出是
0 1 2 3 4
4 3 2 1 0 0 1 2 3 4