1

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
}
  • 2
    insertEnd doesn't return something if head is not null. Also it would be better to have head and tail so you don't have to iterate the whole list every time you add something at the end. – maraca Sep 06 '21 at 11:09
  • 1
    Alternatively you could always add the items at the beginning and then print the list in reverse. – maraca Sep 06 '21 at 11:13
  • Never tought of that, thnx! –  Sep 06 '21 at 11:18

2 Answers2

2

Your insertEnd lacks a return statement for the generic case.

Add the following at the very end of insertEnd:

return head;
trincot
  • 317,000
  • 35
  • 244
  • 286
2
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.

vhdl
  • 58
  • 6