Try   HackMD

2020q3 Homework1 (lab0)

contributed by < chihovrflo >

環境

$ uname -a Linux cial-H55M-UD2H 5.4.0-47-generic #51-Ubuntu SMP Fri Sep 4 19:50:52 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux $ gcc --version gcc (Ubuntu 9.3.0-10ubuntu2) 9.3.0 Copyright (C) 2019 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Programming Task

Modify the code in queue.h and queue.c to fully implement the following functions.

  • q_new : Create a new, empty queue.
  • q_free : Free all storage used by a queue.
  • q_insert_head : Attempt to insert a new element at the head of the queue (LIFO discipline).
  • q_insert_tail : Attempt to insert a new element at the tail of the queue (FIFO discipline).
  • q_remove_head : Attempt to remove the element at the head of the queue.
  • q_size : Compute the number of elements in the queue.
  • q_reverse : Reorder the list so that the queue elements are reversed in order. This function should not allocate or free any list elements (either directly or via calls to other functions that allocate or free list elements.) Instead, it should rearrange the existing elements.

實作過程

  • q_new
    ​​​​queue_t *q_new()
    ​​​​{
    ​​​​    queue_t *new_q = malloc(sizeof(queue_t));
    ​​​​    if (new_q) {
    ​​​​        new_q->size = 0;
    ​​​​        new_q->head = NULL;
    ​​​​        new_q->tail = NULL;
    ​​​​    }
    ​​​​    return new_q;
    ​​​​}
    
    以條件式判斷配置空間是否成功,避免造成初始化錯誤,若配置失敗則回傳 NULL
  • q_insert_head
    ​​​​