如何解决设置 c 中链接列表中可以使用的项目数的限制
我正在尝试弄清楚如何将链表中的项目数从 20 个数组中限制为 5 个,任何想法都会很棒。
解决方法
您需要一个存储列表大小的容器,例如:
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));
}
现在您的插入函数可以在列表已满时返回 NULL
或 false:
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;
}
,
它可以通过多种不同的方式完成。最佳解决方案取决于您的程序,即列表在您的程序中的使用方式。
一种方式是:
// 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;
}
就像 insert
函数增加 size
一样,您需要一个 delete
函数,在删除节点时减少 size
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。