Try   HackMD

2025q1 Homework2 (quiz1+2)

contributed by <kk908676>.

第 1 週測驗題

測驗 一 : 程式碼運作原理

題目核心鏈結串列結構

#include <stddef.h>
typedef struct list_item {
    int value;
    struct list_item *next;
} list_item_t;

typedef struct {
    struct list_item *head;
} list_t;

關鍵操作 list_insert_before 函式的語意如下:

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

測試一:

/* Test inserting at the beginning */
    list_reset();
    my_assert(list_size(&l) == 0, "Initial list size is expected to be zero.");
    for (size_t i = 0; i < N; i++)
        list_insert_before(&l, l.head, &items[i]);
    my_assert(list_size(&l) == N, "Final list size should be N");
    size_t k = N - 1;
    list_item_t *cur = l.head;
    while (cur) {
        my_assert(cur->value == k, "Unexpected list item value");
        k--;
        cur = cur->next;
    }

首先會初始化一個解構指標 head
接著在 head 指向的鏈結串列最前面新增節點,直到 N-1 為止

i = 0







G



head

head



p

0

 



head->p





i = 1







G



head

head



p

1

 



head->p





p_prime

0

 



p:next->p_prime





i = 2







G



head

head



p

2

 



head->p





p_prime

1

 



p:next->p_prime





p_double_prime

0

 



p_prime:next->p_double_prime





以此類推

測試二 :

/* Test inserting at the end */
    list_reset();
    my_assert(list_size(&l) == 0, "Initial list size is expected to be zero.");
    for (size_t i = 0; i < N; i++)
        list_insert_before(&l, NULL, &items[i]);
    my_assert(list_size(&l) == N, "Final list size should be N");
    k = 0;
    cur = l.head;
    while (cur) {
        my_assert(cur->value == k, "Unexpected list item value");
        k++;
        cur = cur->next;
    }

首先會初始化一個解構指標 head
接著在 head 指向的鏈結串列最後面新增節點,直到 N-1 為止

i = 0







G



head

head



p

0

 



head->p





i = 1







G



head

head



p

0

 



head->p





p_prime

1

 



p:next->p_prime





i = 2







G



head

head



p

0

 



head->p





p_prime

1

 



p:next->p_prime





p_double_prime

2

 



p_prime:next->p_double_prime





以此類推

測驗 二 : 程式碼運作原理