Maintaining a pointer to the tail of the linked list would undoubtedly be more efficient than iterating node by node, until the end of the list is found.
Here's a basic example of using a tail pointer:
Code:
#include <stdlib.h>
#include <assert.h>
struct Node
{
int num;
struct Node* next;
};
struct List
{
struct Node* head;
struct Node* tail;
};
void insert(struct List* list, int num)
{
assert(list != 0);
struct Node* elem = malloc(sizeof(struct Node));
elem->num = num;
elem->next = 0;
if (list->head == 0)
{
list->head = elem;
list->tail = list->head;
}
else
{
list->tail->next = elem;
list->tail = elem;
}
}
int main()
{
struct List list = {0, 0};
insert(&list, 23);
insert(&list, 11);
insert(&list, 40);
// ...
return 0;
}
Bookmarks