c beginner
c beginner

Reputation: 1

Set a limit on how many items can be used in a link list in c

I'm trying to figure out how to limit the number of items in a linked list to 5 from an array of 20, any ideas would be great.

Upvotes: 0

Views: 961

Answers (2)

David Ranieri
David Ranieri

Reputation: 41027

You need a container storing the size of the list, something like:

struct node
{
    the data;
    struct node *next;
};

typedef struct
{
    struct node *head;
    struct node *tail;
    size_t size;
} queue;

queue *queue_create(void)
{
    return calloc(1, sizeof(queue));
}

Now your insert function can return NULL or false when the list is full:

bool insert(queue *list, the *data)
{
    if (list->size == 5)
    {
        return false;
    }

    struct node *node = malloc(sizeof *node);

    if (node == NULL)
    {
        return false;
    }
    node->data = data;
    node->next = NULL;
    if (list->head == NULL)
    {
        list->head = node;
    }
    else
    {
        list->tail->next = node;
    }
    list->tail = node;
    list->size++;
    return true;
}

Upvotes: 2

4386427
4386427

Reputation: 44329

It can be done in so many different ways. The best solution depends on your program, i.e. how the list is used in your program.

One way is like:

// This struct is used for the individual nodes in the list
typedef struct node {
    int data;
    struct node * next;
} node;

// This struct is used for managing the list - includes a size counter
typedef struct node_list {
    struct node * head;
    struct node * tail;  // optional
    size_t size;
} node_list;

#define MAX_SIZE 10

int insert(node_list * l, int data)
{
    if (l->size == MAX_SIZE)
    {
        // List is full
        return -1;
    }
    
    // Add code to insert the new node
    
    l->size = l->size + 1; // Increase size
    return 0;
}

int main()
{
    node_list list = {NULL, NULL, 0}; // Create empty list

    if (insert(&list, 42) != 0)
    {
        // Insert failed - list is full
    }
    return 0;
}

Like the insert function increases size, you need a delete function where you decrease size when a node is deleted.

Upvotes: 1

Related Questions