0

Why this program to make a linked list of characters and printing currently added item is showing output twice ?

And I am new to data structure,so i wanna ask another question . Is this implementation in Insert function is done correctly by me?

Code

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

struct Node
{
    char data;
    struct Node *next;
};
struct Node *Head;
void Insert(char data)
{
    struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
    temp->data = data;
    temp->next = Head;
    Head = temp;
    printf("Data in  this Node: %c \n", temp->data);
    
}
int main()
{
    Head=NULL;
    char data;
    while (1)
    {
        printf("Enter a Character : ");
        scanf("%c", &data);
        if (data == '0')
            break;
        Insert(data);
    }
}

Output

PS C:\Users\Dell\OneDrive\Desktop\Data Structure1\Data Structure Text Book> cd "c:\Users\Dell\OneDrive\Desktop\Data Structure1\Data Structure Text Book\Linked list\" ; if ($?) { gcc practice1.c -o practice1 } ; if ($?) { .\practice1 }
Enter a Character : q
Data in  this Node: q
Enter a Character : Data in  this Node:

Enter a Character : w
Data in  this Node: w
Enter a Character : Data in  this Node:

Enter a Character : 0
PS C:\Users\Dell\OneDrive\Desktop\Data Structure1\Data Structure Text Book\Linked list>
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60

1 Answers1

1

This is because when you press q<RETURN>, with <RETURN> being the Return key, that puts a linefeed character in the input stream after the q character.

It's better to read a full line, then inspect that:

char line[128];
while (fgets(line, sizeof line, stdin) != NULL)
{
  Insert(line[0]);
}
unwind
  • 391,730
  • 64
  • 469
  • 606