Я пытаюсь реализовать функцию очереди связанного списка, где мне нужно вставить элемент в начало и в конец очереди, функции: q_insert_head
и q_insert_tail
.
См. Код
queue.h:
typedef struct ELE {
/* Pointer to array holding string.
This array needs to be explicitly allocated and freed */
char *value;
struct ELE *next;
} list_ele_t;
/* Queue structure */
typedef struct {
list_ele_t *head; /* Linked list of elements */
list_ele_t *tail;
size_t size;
/*
You will need to add more fields to this structure
to efficiently implement q_size and q_insert_tail
*/
} queue_t;
queue.c:
queue_t *q_new()
{
queue_t *q = malloc(sizeof(queue_t));
if (q == NULL)
{
return NULL;
}
/* What if malloc returned NULL? */
q->head = q->tail = NULL;
q->size = 0;
return q;
}
/* Free all storage used by queue */
void q_free(queue_t *q) {
/* How about freeing the list elements and the strings? */
if (q==NULL)
return;
list_ele_t *tmp_next;
while(q->head !=NULL)
{
tmp_next = q->head->next;
free(q->head->value);
free(q->head);
q->head = tmp_next;
}
free(q);
}
/*
Attempt to insert element at head of queue.
Return true if successful.
Return false if q is NULL or could not allocate space.
Argument s points to the string to be stored.
The function must explicitly allocate space and copy the string into it.
*/
bool q_insert_head(queue_t *q, char *s)
{
list_ele_t *newh;
/* What should you do if the q is NULL? */
if (q == NULL) {
return false;
}
newh = (list_ele_t *) malloc(sizeof(list_ele_t));
if (newh == NULL) {
return false;
}
size_t s_len = strlen(s) + 1; // Don't forget the \0!!!!!!!
/* Don't forget to allocate space for the string and copy it */
newh->value = (char *) malloc(s_len * sizeof(char));
if (newh->value == NULL) {
free(newh);
return false;
}
strcpy(newh->value, s);
/* What if either call to malloc returns NULL? */
newh->next = q->head;
if (newh->next == NULL) { // Change the tail
q->tail = newh;
}
q->head = newh;
q->size++;
return true;
}
/*
Attempt to insert element at tail of queue.
Return true if successful.
Return false if q is NULL or could not allocate space.
Argument s points to the string to be stored.
The function must explicitly allocate space and copy the string into it.
*/
bool q_insert_tail(queue_t *q, char *s)
{
/* You need to write the complete code for this function */
/* Remember: It should operate in O(1) time */
list_ele_t *temp;
temp = (list_ele_t *) malloc(sizeof(list_ele_t));
if(q == NULL)
{
return false;
}
if(temp == NULL){
return false;
}
long int slen = strlen(s) + 1;
temp->value = (char *) malloc(sizeof(char) * slen);
if(temp->value == NULL)
{
free(temp);
return false;
}
strcpy(temp->value,s);
if(q->tail!= NULL)
{
q->tail->next = temp;
}
else
{
q->head = temp;
}
q->tail = temp;
temp->next = NULL;
q->size++;
return true;
}
Вы должны быть в состоянии вставить в начало / конец очереди, но всегда выдает ошибки в
ERROR: Segmentation fault occurred. You dereferenced a NULL or invalid pointer.
Я понятия не имею, почему, и я полностью застрял.Есть идеи?