[英]Linked lists in C program terminates during insertion
struct node
{
char key;
struct node *next;
};
typedef struct node *node;
struct list
{
node head;
};
typedef struct list *list;
node CREATE(char k)
{
node tmp;
tmp = (node)malloc(sizeof(struct node));
if (tmp == NULL)
{
exit(0);
}
tmp->key = k;
tmp->next = NULL;
return temp;
}
void InsertAtBeg(list L, char k) //insert at the beginning
{
node x;
x = CREATE(k); //creating a node
x->next = L->head; //inserting at the beginning
L->head = x;
}
This is the main function这是主要功能
int main()
{
list L;
char k;
char x, y;
char ch = 'q';
while(ch!='e') //termination condition
{
scanf("%c ",&ch);
switch(ch)
{
case 'i': //first case
scanf("%c",&k);
InsertAtBeg(L,k);
break;
.............//more options are below but none of them work including first
}
}
}
Once I input the two characters-choice and the key for the new node, the program breaks the loop even though I have not given the termination character -'e';一旦我输入了两个字符选择和新节点的键,即使我没有给出终止字符 -'e',程序也会中断循环; Is it a problem with linked list implementation or with scanf function?是链表实现的问题还是 scanf 函数的问题?
I think code works now.我认为代码现在有效。 It was required to initialize L->head as null before the creation of the linked list.在创建链表之前需要将 L->head 初始化为 null。
删除多余的空白 scanf("%c",&ch);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.