Try   HackMD

2024q1 Homework1 (lab0)

contributed by < Lushengjhou0315 >

詳閱作業規範,注意細節。

開發環境

$ gcc --vesion
gcc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0

$ lscpu
Architecture:            x86_64
  CPU op-mode(s):        32-bit, 64-bit
  Address sizes:         46 bits physical, 48 bits virtual
  Byte Order:            Little Endian
CPU(s):                  20
  On-line CPU(s) list:   0-19
Vendor ID:               GenuineIntel
  Model name:            13th Gen Intel(R) Core(TM) i5-13500
    CPU family:          6
    Model:               191
    Thread(s) per core:  2
    Core(s) per socket:  14
    Socket(s):           1
    Stepping:            2
    CPU max MHz:         4800.0000
    CPU min MHz:         800.0000
    BogoMIPS:            4992.00

指定的佇列操作

queue.c

將目標完成的 queue.c 打開以後,除了確認預期目標中,未完整程式的功能以及需求,從 queue.h 中確認輸入參數所代表的意思與型別。標頭檔中 list.h 的內容也有看,其中有許多功能可以拿來利用,因此在實作的部分會使用到其中的內容進行實作

  1. 無論標題和內文中,中文和英文字元之間要有空白字元 (對排版和文字搜尋有利)
  2. 改進你的漢語表達

q_new

struct list_head *q_new()
{
    struct list_head *new_queue = malloc(sizeof(struct list_head));
    if(!new_queue){
    	return NULL;   //分配記憶體失敗
    }
    INIT_LIST_HEAD(new_queue);
    return new_queue;
}

首先使用了 malloc 配置了記憶體,根據 harness.h 的描述,記憶體有可能配置失敗,會回傳 NULL ,因此需要加上判斷。

static inline void INIT_LIST_HEAD(struct list_head *head)
{
    head->next = head;
    head->prev = head;
}

在這邊還利用 INIT_LIST_HEAD 進行 head 的初始化,由於佇列的鏈結串列是雙向的,現在只有節點,因此向前以及向後的指標都指向自己。

q_free

void q_free(struct list_head *head) 
{
    if (!head){
    	return;
    }
    if (list_empty(head)){
    	free(head);
    	return;
    }
    element_t *entry, *safe;
    list_for_each_entry_safe(entry, safe, head, member){
    	list_del(entry);
    	free(entry);
    }
    free(head);
    return
}

考慮了幾個可能性

  • head 不存在,直接回傳。
  • head 為空佇列,釋放此記憶體空間,再回傳。