c中並沒有類似c++或其他高級語言中數組的pop push insert操作 只能每次遇到這種情況都先手工實現鏈表或棧再操作嗎?


預先估計一下上限然後按照上限去malloc一塊內存用就好了。估計不出來的話,就只能手撕一個vector了。
數據結構的書上都會有講的吧, 最簡單直接的就是 realloc + memmove,如果是純 C 沒得 memmov 用,要麼自己實現一個,要麼 malloc+memcpy+free。


一般只往末尾增刪東西的,你都可以開個足夠大的數組,然後拿個變數記錄尾元素的坐標。
這就是鏈表的好處吧,如果數組可以實現這些功能,要鏈表有什麼用,菜鳥弱弱的回答。
給你一段我寫的代碼吧。這是關於一個 queue 到了 capacity 後自動 grow 的

/**
* Increase internal buffer size to the next legal capacity when the actual size
* meets the current capacity.
*/
static void grow() {
int old_cap = cap;

cap = (int)(cap * (1 + GROWTH_FACTOR));
// create the new inner buffer with the new capacity
int * new_queue = (int *)malloc(sizeof(int) * cap);
// copy the current inner buffer to the new inner buffer
// starting from front to tail
for (int i = 0; i &< size; ++i) { new_queue[i] = q_buff[(i + front_index) % old_cap]; } // destroy old buffer free(q_buff); // replace q_buff = new_queue; // reset front, tail front_index = 0; tail_index = size - 1; }

關於 insert,你需要從 index 開始,將後續的元素後移一位。如果當前 size + 1 超過了數組的 length,你就需要上面的 grow 方法重新創建一個新數組。


推薦閱讀:
相關文章