0

I'm trying this simple code which asks a user for string input. As it receives an input it then tries to copy each element of the string into different location in a linked list. Everything works just fine (I think) but when i print the linked list, the screen doesnt show any out put. Any idea why is this happening?

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

struct node {
char data;
struct node* next;
};

struct node* head = NULL;

void insert(char);
void print();

void main() {
char str1[20];
int i;
printf("Enter the string\n");
fgets(str1,20,stdin);

int len = strlen(str1);
printf("%d\n",len);
for(i=0;i<len;i++) {
insert(str1[i]);
}
print();
}

void insert(char str) {
struct node* temp = (struct node*)malloc(sizeof(struct node));

struct node* temp1 = head;
        while(temp1!=NULL) {
            temp1 = temp1->next;
        }
    temp->data = str;
    temp1 = temp;

}

void print() {

struct node *temp;
temp = head;

while(temp!=NULL) {
    printf("%c ",temp->data);
    temp = temp->next;
}
}
Aiguo
  • 3,416
  • 7
  • 27
  • 52

2 Answers2

2

You never set head to anything, it will always be NULL. So, you're not creating a list, but a group of unlinked floating nodes.

On another note, don't cast the result of malloc

On yet another note, no need to go through the entire list for every insert - you can keep a tail pointer along with the head, so adding to the end is done without a loop.

Community
  • 1
  • 1
mtijanic
  • 2,872
  • 11
  • 26
1
void insert(char str) {
    struct node* temp = (struct node*)malloc(sizeof(struct node));
    temp->data = str;
    temp->next = NULL;

    if(head){//head != NULL
        struct node* temp1 = head;
        while(temp1->next != NULL) {//search last element
            temp1 = temp1->next;
        }
        temp1->next = temp;//insert new node
    } else {
        head = temp;//if head == NULL then replace with new node
    }
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70