contributed by <kk908676
>.
題目核心鏈結串列結構
#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
函式的語意如下:
測試一:
/* 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
時
當 i = 1
時
當 i = 2
時
以此類推…
測試二 :
/* 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
時
當 i = 1
時
當 i = 2
時
以此類推…