2016-08-14 25 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