CMU 15-213 ICS Lab 0. C Programming Lab

这篇博客介绍了如何使用C语言实现链表结构的队列操作,包括创建空队列、释放空间、在队列首尾插入元素、移除头元素、获取队列长度以及队列反转等功能。其中,q_insert_tail 和 q_size 操作要求时间复杂度为 O(1)。文章提供了一种可能的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

来源: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:

  1. 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;
  1. 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值