Вам не нужно использовать 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