linked list that add element at the begining i want to add at begining but it only accept first element and then treminate it does not accept the other elements whats wrong with while loop
#include <stdio.h>
typedef struct node_type {
int data; struct node_type *next;
} node;
typedef node* list;
void main() {
list head,temp; int n; char ch;
head = NULL;
printf("\n Enter the data:(y/n):");
scanf("%c", &ch);
while (ch == 'y' || ch == 'Y') {
printf("\n Enter Element:");
scanf("%d", &n);
temp = (list) malloc(sizeof(node));
temp->data = n;
temp->next = head;
head = temp;
printf("\n Enter more data:");
scanf("%c", &ch);
}
temp = head;
while (temp != NULL) {
printf("%d", temp->data);
temp = temp->next;
}
}
最佳答案
对于初学者来说,根据 C 标准,不带参数的 main 函数应声明如下
int main( void )
对变量 ch
调用函数 scanf
的格式字符串必须如下所示
scanf( " %c", &ch );
^^^^^^
在这种情况下,包括换行符在内的空白字符将被跳过。否则该函数将返回控制字符。另外你应该检查流是否有结尾。
while 循环看起来像
printf( "\nEnter the data:(y/n): " );
while ( scanf( " %c", &ch ) == 1 && ( ch == 'y' || ch == 'Y' ) )
{
printf( "\nEnter Element: " );
scanf( "%d", &n );
temp = (list) malloc( sizeof( node ) );
if ( temp != NULL )
{
temp->data = n;
temp->next = head;
head = temp;
}
printf( "\nEnter more data: " );
}
关于c - 这有什么问题?这段代码没有在链表的开头插入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38941926/