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;
}
}

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Something that would have been revealed immediately with a debugger, so OP gets a downvote.
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
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.