From 311e71aeecb1b958b16efdf3d155dcc4b037699a Mon Sep 17 00:00:00 2001 From: Aaron Liao Date: Sat, 16 Mar 2024 17:13:58 +0800 Subject: [PATCH] Implement two types of q_remove functions Implement the following remove functions: - q_remove_head(): Remove an element from the head of the queue - q_remove_tail(): Remove an element from the tail of the queue --- queue.c | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/queue.c b/queue.c index 9c6eb61cc..42757d3cd 100644 --- a/queue.c +++ b/queue.c @@ -68,13 +68,36 @@ bool q_insert_tail(struct list_head *head, char *s) /* Remove an element from head of queue */ element_t *q_remove_head(struct list_head *head, char *sp, size_t bufsize) { - return NULL; + if (!head || list_empty(head)) + return NULL; + + element_t *target = list_first_entry(head, element_t, list); + if (sp) { + int orig_len = strlen(target->value); + int copy_len = (orig_len < bufsize - 1) ? orig_len : bufsize - 1; + strncpy(sp, target->value, copy_len); + sp[copy_len] = '\0'; + } + + list_del(&target->list); + return target; } /* Remove an element from tail of queue */ element_t *q_remove_tail(struct list_head *head, char *sp, size_t bufsize) { - return NULL; + if (!head || list_empty(head)) + return NULL; + + element_t *target = list_last_entry(head, element_t, list); + if (sp) { + int orig_len = strlen(target->value); + int copy_len = (orig_len < bufsize - 1) ? orig_len : bufsize - 1; + strncpy(sp, target->value, copy_len); + sp[copy_len] = '\0'; + } + list_del(&target->list); + return target; } /* Return number of elements in queue */