user13395631
user13395631

Reputation:

Appending a new node to linked list

Basically what title says, Im trying to append (add to end of my list). my BuildList function takes in a size parameter that determines how many nodes the list will have. my problem is with my append function. So if I have 5 as my head, how do I fix my append function so that random numbers will be added after 5?

typedef struct Node
{
    int value;
    struct Node* next;
} Node;

Node *createNode( int num )
{
    Node *ptr;
    ptr = (Node *) malloc( sizeof( Node ) );

    ptr->value = num;
    ptr->next = NULL;

    return ptr;
}
Node* append (Node* head, Node* newNode)
{


    if (head == NULL)
        return newNode;

    while (head -> next != NULL);

    head -> next = newNode;
    return head;
}
Node* buildList (int size)
{
    Node* newNode = (Node*) malloc (sizeof(Node));
    Node* head = NULL;

    for (int i = 0; i < size; i++)
    {
        Node* newNode = createNode (rand () % 10);
        head = append (head, newNode);
    }
    return head;
}

Upvotes: 0

Views: 146

Answers (2)

Baxter Lopez
Baxter Lopez

Reputation: 1129

You just need to modify your while, why do you have an empty instruction there? If the head is not NULL then you will never exit:

while (head -> next != NULL)
{
    head = head -> next;
}

Upvotes: 0

Chris Loonam
Chris Loonam

Reputation: 5745

Well, the most glaring issue is this

while (head -> next != NULL);

I believe you meant to write something like this

Node *tmp = head;
while (tmp -> next != NULL) {
    tmp = tmp->next;
}
tmp->next = newNode;

You don't want to modify head here since you return it later in the function. If you didn't use tmp, head would always point to the penultimate node in the list.

Upvotes: 2

Related Questions