Search code examples
clistalgorithmstructure

Inserting in Linked List goes wrong


I can't figure out what's wrong with my code. I have experience with Linked lists but today I don't know what's wrong.

When I want to print the Linked list using the printNodes() function, it doesn't print the first two nodes. I'm inserting it in a wrong way but don't know where I make the mistake.

struct node *makeNode(int data)
{
    struct node *temp = (struct node *)malloc(sizeof(struct node) * 1);
    temp->data = data;
    temp->next = NULL;
    return temp;
}

struct node *insertEnd(int data, struct node *head)
{
    struct node *temp = makeNode(data);
    if (head == NULL)
    {
        return temp;
    }

    struct node *loop = head;
    while (loop->next)
    {
        loop = loop->next;
    }
    loop->next = temp;
}

void printNodes(struct node *head)
{

    struct node *loop = head;
    while (loop)
    {
        printf("%d ", loop->data);
        loop = loop->next;
    }
}

int main()
{
    struct node *head = NULL;
    head = insertEnd(5, head);
    head = insertEnd(10, head);
    head = insertEnd(15, head);
    head = insertEnd(20, head);

    printNodes(head);
    printf("%d", head->data); <-- The data inside the head node doesn't get printed
}

Solution

  • struct node *insertEnd(int data, struct node *head)
    {
        struct node *temp = makeNode(data);
        if (head == NULL)
        {
            return temp;
        }
    
        struct node *loop = head;
        while (loop->next)
        {
            loop = loop->next;
        }
        loop->next = temp;
        return head; //I think you missed this in your implementation
    }
    

    Alternatively you could always add the items at the beginning and then print the list in reverse. As mentioned by @maraca in the comment section. Please visit here to see different ways to insert node in the linked list.