0

Sometime back I asked a question about linked list and got nice replies...Now I've written a new code using the suggestions but I've run into an error. The code is:

#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
    int data;
    struct node *next;
}node;
node *mknode()
{
    return malloc(sizeof(node));
}
void create(node* h, int num)
{
    int i;
    node *temp=h;
    for(i=0;i<num;i++)
    {
        temp->data=i;
        if(i==(num-1))
            temp->next=NULL;
        else
            temp->next=mknode();
        temp=temp->next;
    }
}
node* add_end(node *h,int num)
{
    node *temp;
    if(h==NULL)
    {
        h=mknode();
        temp=h;
        create(h,num);
    }
    else
    {
        temp=h;
        while(h!=NULL){
            h=h->next;}
        h=mknode();
        create(h,num);
    }
    return temp;
}
void display(node *h)
{
    node *temp=h;
    while(temp!=NULL)
    {
        printf("%d->",temp->data);
        temp=temp->next;
    }
}
int main()
{
    node *head=NULL;
    int num;
    scanf("%d",&num);
    head=add_end(head,num);
    head=add_end(head,num);
    display(head);
    //printf("%d",list_len(head));
    free(head);
    return 0;
}

Now since I've called add_end twice for an input of 3 the output should be 0->1->2->0->1->2-> But instead I'm getting 0->1->2->

I've checked this much that the FOR loop inside create function is running 2n times for an input of n. So the problem is that display function encounters a NULL but I can't figure out where in the code is it happening.

All help appreciated. Thanking in advance -user1614886

1 Answer 1

3

In add_end() you do not link the nodes correctly.

[blah blah]
else
{
    temp=h;
    while(h!=NULL){
        h=h->next;}
    h=mknode();
    create(h,num);
}

You advance h until it is NULL but you should only move until h->next == NULL and append your next list there.

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

3 Comments

Thanks Mehrwolf for your reply...I did what you asked...but to make the code work correctly I had to change h=mknode(); to h->next=mknode(); and pass h->next in create function instead of h...so ultimately isn't it doing the same thing EDIT:No they are different...figured it out :P
@user1614886: That was what I intended. First move until h->next == NULL and then append the new end at h->next. This makes the connection between the end of the old list h and the new list h->next.
@Meherwolf: After few more minutes of thinking everything makes sense now. Thanks again.

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.