I'm trying to insert n of characters in a linked list.
#include <stdio.h>
#include <stdlib.h>
//Declare our linked list:
struct node{
char ch;
struct node* link;
};
//we now intiate our head node the node which will identify our likedlist
struct node* head;
//prototype the insert function
void insert(char a);
//prototype the print function
void print();
int main() {
//set the head to NULL
head =NULL;
char x;
int i,n;
printf("Enter how many Letter you wish for:\n");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Enter the letter:\n");
scanf("%c",&x);
insert(x);
print();
}
return 0;
}
//construct out insert function
void insert(char a){
//we create a new block of memory in the heap here
struct node* temp = (struct node*)malloc(sizeof(struct node));
//store the passed arrgument in ch
temp->ch=a;
//fill the other room of the created block with the location/link
//the previous node/block
temp->link=head;
//change the head to point to our newly created block
head=temp;
}
void print(){
//store the value of the head so we don't lose the head
struct node* temp1=head;
//iterate through the nodes ant print the data in it until we hit the NULL value
printf("[");
while(temp1->link != NULL){
printf("%c",temp1->ch);
//will go to the next node
temp1=temp1->link;
}
printf("]\n");
}
But the output is just a mess, what I'm doing wrong? sample of the output: Enter how many Letter you wish for: 3 Enter the letter: [] Enter the letter: F [F] Enter the letter: [ F]