来源:CS:APP
针对以下链表结构,实现以下功能,可以修改链表元素的定义。
/* Linked list element */
typedef struct ELE {
char *value;
struct ELE *next;
} list_ele_t;
/* Queue structure */
typedef struct {
list_ele_t *head; /* Linked list of elements */
} queue_t;
- q_new: 创建空队列。
- q_free: 释放所有队列所占所有空间。
- q_insert_head: 在队列首部添加元素 (LIFO).
- q_insert_tail: 在队列结尾添加元素(FIFO discipline). (时间复杂度要求为O(1))
- q_remove_head: 移除头元素,并释放空间。
- q_size: 返回队列长度(时间复杂度要求为O(1))。
- q_reverse: 将队列反转,不允许新分配或释放空间。
One Possible Solution:
- definitions(queue.h)
typedef struct ELE {
/* Pointer to array holding string.
This array needs to be explicitly allocated and freed */
char *value;
// struct ELE *tail;
struct ELE *next;
} list_ele_t;
/* Queue structure */
typedef struct {
list_ele_t *head; /* Linked list of elements */
/*
You will need to add more fields to this structure
to efficiently implement q_size and q_insert_tail
*/
list_ele_t *tail;
int n;
} queue_t;
- functions
/*
* Code for basic C skills diagnostic.
* Developed for courses 15-213/18-213/15-513 by R. E. Bryant, 2017
* Modified to store strings, 2018
*/
/*
* This program implements a queue supporting both FIFO and LIFO
* operations.
*
* It uses a singly-linked list to represent the set of queue elements
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "harness.h"
#include "queue.h"
/*
Create empty queue.
Return NULL if could not allocate space.
*/
queue_t *q_new()
{
queue_t *q = malloc(sizeof(queue_t));
/* What if malloc returned NULL? */
if(q == NULL)
return q;
q->head = NU