Skip to content

Commit 5a1e92d

Browse files
committed
Implement q_insert_head & q_insert_tail
This commit implements the function to allocate a new element into the head or tail of the list. Using list_add & list_add_tail to implement this two funtions. If allocated FAILED, it will free the new element and return false to avoid memory leak. Change-Id: I10544fc8019a7d7e6b1fd52d8dd4588e486c1740
1 parent a0800a1 commit 5a1e92d

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

queue.c

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,30 @@ void q_free(struct list_head *head)
3636
/* Insert an element at head of queue */
3737
bool q_insert_head(struct list_head *head, char *s)
3838
{
39+
if (!head || !s)
40+
return false;
41+
element_t *node = malloc(sizeof(element_t));
42+
node->value = strdup(s);
43+
if (!node->value) {
44+
free(node);
45+
return false;
46+
}
47+
list_add(&node->list, head);
3948
return true;
4049
}
4150

4251
/* Insert an element at tail of queue */
4352
bool q_insert_tail(struct list_head *head, char *s)
4453
{
54+
if (!head || !s)
55+
return false;
56+
element_t *node = malloc(sizeof(element_t));
57+
node->value = strdup(s);
58+
if (!node->value) {
59+
free(node);
60+
return false;
61+
}
62+
list_add_tail(&node->list, head);
4563
return true;
4664
}
4765

0 commit comments

Comments
 (0)