我将数字插入链表开头的代码无法编译
My code for inserting numbers to the start of linked list doesn't compile
这是代码
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node* next;
}node;
node* head;// global variable can be accessed anywhere
void Insert(int x);//function to insert the number in start
void print();//function to print them
int main()
{
head = NULL;// empty list
printf("How many numbers?\n");
int n,i,x;
scanf("%i", &n);
for(i = 0; i < n; i++)
{
printf("Enter the Number\n");
scanf("%i", &x);
Insert(x);
}
print();
}
void Insert(int x)
{
node* temp = malloc(sizeof(node));
temp->data = x;
temp->next = head;
head = temp;
}
void print()
{
node* temp = head;
print("List is: ");
while(temp != NULL)
{
printf("%d ",temp->data);
temp = temp->next;
}
printf("\n");
}
所以我尝试在 VS Code 中编译代码,它询问有多少个数字,然后要求输入数字,在输入第一个数字后,程序停止。
所以我尝试在 CS50 ide 中编译,这是我得到的错误-
linkedlist1.c:41:1: error: all paths through this function will call itself [-Werror,-Winfinite-recursion]
{
^
第 41 行是函数的第一个花括号 void print()
为什么会这样? & 我该如何解决?
通话中
print("List is: ");
函数内部
void print()
无条件是无限递归。
你的意思可能是
printf("List is: ");
(用 f
调用 printf
,而不是 print
)
为避免此类错误,您应该将不带参数的函数标记为不显式带参数。这可以通过使用 void
作为参数来完成,例如
void print(void)
这是代码
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node* next;
}node;
node* head;// global variable can be accessed anywhere
void Insert(int x);//function to insert the number in start
void print();//function to print them
int main()
{
head = NULL;// empty list
printf("How many numbers?\n");
int n,i,x;
scanf("%i", &n);
for(i = 0; i < n; i++)
{
printf("Enter the Number\n");
scanf("%i", &x);
Insert(x);
}
print();
}
void Insert(int x)
{
node* temp = malloc(sizeof(node));
temp->data = x;
temp->next = head;
head = temp;
}
void print()
{
node* temp = head;
print("List is: ");
while(temp != NULL)
{
printf("%d ",temp->data);
temp = temp->next;
}
printf("\n");
}
所以我尝试在 VS Code 中编译代码,它询问有多少个数字,然后要求输入数字,在输入第一个数字后,程序停止。 所以我尝试在 CS50 ide 中编译,这是我得到的错误-
linkedlist1.c:41:1: error: all paths through this function will call itself [-Werror,-Winfinite-recursion]
{
^
第 41 行是函数的第一个花括号 void print()
为什么会这样? & 我该如何解决?
通话中
print("List is: ");
函数内部
void print()
无条件是无限递归。
你的意思可能是
printf("List is: ");
(用 f
调用 printf
,而不是 print
)
为避免此类错误,您应该将不带参数的函数标记为不显式带参数。这可以通过使用 void
作为参数来完成,例如
void print(void)