c - 这有什么问题?这段代码没有在链表的开头插入元素

标签 c

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/

相关文章:

arrays - C 压缩器 - 数组下标的类型为 char

无法评论//代码块

c - 将 double 分为符号、指数和尾数

c - a+b+c会不会这样操作 : a+c+b?

c - 问题查找字符串中给定子字符串的出现次数

c - 如果 argp_program_bug_address 存在或不存在,GNU Argp 如何改变其行为?

c - 在 C 中使用 choice as char 进行 while 循环

c - Windows 和 Windows 窗体

c - 辅助线程中的信号处理

代码注释现在会生成编译器错误