开始设计
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
#include <c_PtrLinkBag.h>
|
||||
#include <c_Memory.h>
|
||||
|
||||
c_err_t c_PtrLinkBag_Init(c_PtrLinkBag_t* self) {
|
||||
if (!self) return C_ERR_PARAM;
|
||||
self->head= NULL;
|
||||
return C_ERR_SUCCESS;
|
||||
}
|
||||
|
||||
void c_PtrLinkBag_Destroy(c_PtrLinkBag_t* self) {
|
||||
if (!self) return;
|
||||
c_PtrLinkBagNode_t* p = self->head;
|
||||
while (p) {
|
||||
c_PtrLinkBagNode_t* q = p->next;
|
||||
C_FREE(p);
|
||||
p = q;
|
||||
}
|
||||
self->head = NULL;
|
||||
}
|
||||
|
||||
c_err_t c_PtrLinkBag_Add(c_PtrLinkBag_t* self, void* item) {
|
||||
if (!self) return C_ERR_PARAM;
|
||||
c_PtrLinkBagNode_t* p;
|
||||
C_NEW(p);
|
||||
if (!p) {
|
||||
return C_ERR_NOMEM;
|
||||
}
|
||||
p->ptr = item;
|
||||
p->next = self->head;
|
||||
self->head = p;
|
||||
return C_ERR_SUCCESS;
|
||||
}
|
||||
|
||||
c_err_t c_PtrLinkBag_Remove(c_PtrLinkBag_t* self, const void* item) {
|
||||
if (!self) return C_ERR_PARAM;
|
||||
c_PtrLinkBagNode_t** curr = &self->head;
|
||||
while (*curr != NULL) {
|
||||
if ((*curr)->ptr == item) {
|
||||
c_PtrLinkBagNode_t* entry = *curr;
|
||||
*curr = entry->next;
|
||||
C_FREE(entry);
|
||||
return C_ERR_SUCCESS;
|
||||
}
|
||||
curr = &(*curr)->next;
|
||||
}
|
||||
|
||||
return C_ERR_NOT_FOUND;
|
||||
}
|
||||
|
||||
void c_PtrLinkBagIter_Remove(c_PtrLinkBagIter_t* self) {
|
||||
// 防呆檢查:確保迭代器有效,且當前指向的節點不為空
|
||||
if (!self || !self->node || !*(self->node)) return;
|
||||
|
||||
c_PtrLinkBagNode_t* to_delete = *(self->node);
|
||||
|
||||
// 將當前結構中維護的指標(可能是上一節點的 next,或是 bag 的 head)
|
||||
// 修改為指向下一個節點,直接從鏈結串列中斷開
|
||||
*(self->node) = to_delete->next;
|
||||
|
||||
// 釋放記憶體
|
||||
C_FREE(to_delete);
|
||||
|
||||
// 注意:此時 self->node 自動更新指向了原本的下一個節點
|
||||
// 使用者不需要再呼叫 Next(),即可直接對新節點進行 Get() 或再次 Remove()
|
||||
}
|
||||
Reference in New Issue
Block a user