gator
gator

Reputation: 3523

Append entry to end of linked list

I want to add an entry to a linked list at the end, but am having trouble dealing with pointers. Here's my linked list:

struct list {
    int val;
    list *next;
};

I declare a list aList globally:

struct list *aList;

And have a function to add values to the list:

void add(int var) {
    struct list *temp = aList;
    if (temp == NULL) { //if aList is empty
        temp = malloc(sizeof(struct list));
        temp->val = var; //add it to first spot
        temp->next = NULL;
    } else { //if aList is not empty
        while (temp->next != NULL) { //find the first empty spot
            temp = temp->next;
        }
        temp = malloc(sizeof(struct list));
        temp->val = var; //add it to empty spot
        temp->next = NULL;
    }
}

I'm really lost with the pointers. I want to add to aList so I need to make a temp list pointing to it and add to that (any changes reflect on aList). Without using a temp list, I lose the structure of the list and it will contain 1 or 0 elements irrespective of how many I've added.

Say I want to do the below:

for (int i = 0; i < 5; i++) { add(i); }

I want aList to be 1->2->3->4->5->NULL and be able to access it starting from 1.

Upvotes: 1

Views: 174

Answers (1)

rohit89
rohit89

Reputation: 5773

while (temp->next != NULL) { //find the first empty spot
        temp = temp->next;
    }
    temp = malloc(sizeof(struct list));

You're overwriting the last element when you do this.

Instead, you need to assign it to a new node.

struct list *newnode = malloc(sizeof(struct list));
// Fill newnode
temp->next = newnode;

Upvotes: 2

Related Questions