为什么while循环不适用于此链接列表程序?

时间:2018-07-03 17:08:35

标签: c loops linked-list

请帮助我了解以下代码中while循环为什么不起作用的原因:

     #include<stdio.h>
     #include<stdlib.h>
     typedef struct node_type{
                int data;
                struct node_type *next;
    }node;

    typedef node *list;
    list head;

    void main()
    {
            list temp,new;
            head=NULL;
            int n;
            char ch;
            temp=(list) malloc(sizeof(node));
            printf("\nGive data: ");
            scanf("%d",&temp->data);
            head=temp;
            printf("\n");
            printf("Enter Data? (y/n): ");
            scanf("%c",&ch);while(getchar()!='\n');
            while(ch=='y'||ch=='Y')
            {
                    new=(list) malloc(sizeof(node));
                    printf("Give data: ");
                    scanf("%d",&new->data);while(getchar()!='\n');
                    temp->next=new;
                    temp=new;
                    printf("\nEnter more data(y/n): ");
                    scanf("%c",&ch);while(getchar()!='\n');
            }
            temp->next=NULL;
            traverse(head);
}

输出如下: 给出数据:2

输入更多数据(y / n):y

2

,程序在此处终止。

1 个答案:

答案 0 :(得分:0)

您不需要在while(getchar()!='\n');之前的任何地方使用scanf()。这导致程序终止。您可以改用scanf("\n%c", &ch);。此外,建议在new->next = NULL;之后写入new = (list)malloc(sizeof(node));。 此外,您还会错过traverse()函数。

尝试此修改后的代码:-

#include <stdio.h>
#include <stdlib.h>
typedef struct node_type
{
        int data;
        struct node_type *next;
} node;

typedef node *list;
list head;

void traverse(node *head) // This is simple traverse function just to demonstrate code.
{
        while (head != NULL)
        {
                printf("%d  ", head->data);
                head = head->next;
        }
}
void main()
{
        list temp, new;
        head = NULL;
        int n;
        char ch;
        temp = (list)malloc(sizeof(node));
        temp->next = NULL;
        printf("\nGive data: ");
        scanf("%d", &temp->data);
        head = temp;
        printf("\n");
        printf("Enter Data? (y/n): ");
        scanf("\n%c", &ch);
        while (ch == 'y' || ch == 'Y')
        {
                new = (list)malloc(sizeof(node));
                new->next = NULL;
                printf("Give data: ");
                scanf("%d", &new->data);
                new->next = NULL;
                temp->next = new;
                temp = new;
                printf("\nEnter more data(y/n): ");
                scanf("\n%c", &ch);
        }
        temp->next = NULL;
        traverse(head);
}

输出:-

Give data: 2

Enter Data? (y/n): y
Give data: 22

Enter more data(y/n): y
Give data: 32

Enter more data(y/n): n

 List is :  2  22  32