2016-08-14 48 views
-3

链表,在我想在begining添加开始时 添加元素,但它只能接受第一个元素,然后 treminate 它不接受其他元素什么是错用while循环什么问题呢?这个代码不链表的开头插入元素

#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; 
    } 
} 
+3

请注意,执行'fflush(stdin)'是* undefined behavior *。一些“标准”库将其添加为扩展名,但如果可能的话避免它。 –

+2

你做了什么调试? –

+0

由于缺少标点符号,无法解析问题...... *叹*。我觉得这是... – alk

回答

1

你应该改变的方式,你看y/n回应:

scanf(" %c", &ch); 

在格式字符串中添加空格可指示scanf跳过任何空格字符,包括您尝试摆脱fflush(stdin);(将调用未定义的行为)的挂起换行符。

同时检查返回值scanf():应该是1,否则转换不成功。

2

对于按照不带参数的C标准函数main首先应声明如下

int main(void) 

功能scanf为变量ch调用的格式字符串必须看起来像

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: "); 
} 
+0

测试scanf的返回值(“%d”,&n);'是可取的,铸造malloc()的返回值不是 – chqrlie

0

这是一个有点修改后的代码。

#include <stdio.h> 
#include <stdlib.h> 

typedef struct node_type { 
    int data; 
    struct node_type *next; 
}list; 

int 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); 
     if(head == NULL) { 
      head = (list*) malloc(sizeof(list)); 
      head->data = n; 
      head->next = NULL; 
     } 
     else { 
      temp = (list*) malloc(sizeof(list)); 
      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; 
    } 
    return 0; 
} 

编辑:我也做过同样的事情,@Vlad和@chqrlie提及。

+0

代码没有缩进,'head == NULL'测试没用,'else'分支可以正确处理所有情况 – chqrlie

-1

NULL不stdio.h定义,你应该使用#define宏或通过使用stddef.hstdlib.h。它会更好地使用fflush(stdin)因为它清除输入缓冲器(这消除unexpexted错误,而与scanf()处理手动定义它字符和整数)。它被预定义在stdio.h

+1

'NULL' **在** 以及其他标准标题例如'','','',''可以用'scanf(“%* [^ \ n]”); scanf(“%*”)调用未定义的行为。 C“);' – chqrlie