兩道環形佇列設計的題。
leetcode 622. design circular queue
leetcode 641. design circular deque
一道題是環形 queue 的設計,circular queue is also called "ring buffer";另一道是環形 deque 的設計。給出了 api 要求給出實現。
兩道題實際上是一樣的,開闢對應大小的緩衝區,然後環形的話使用取餘操作來實現即可。
這裡我們使用 head & tail 指向首尾元素,並額外多分配乙個元素的空間作為哨兵,用於區分空佇列和滿佇列。
這裡我們只給出 deque 的實現**,因為 queue 實際上是限定了只能使用 deque 的部分功能,queue 的實現只需要擷取 deque 對應部分的實現即可。
/*
* * [641] design circular deque
*/// @lc code=start
class mycirculardeque
~mycirculardeque()
/** adds an item at the front of deque. return true if the operation is successful. */
bool insertfront(int value)
head = (head - 1 + cap) % cap;
data[head] = value;
return true;
}/** adds an item at the rear of deque. return true if the operation is successful. */
bool insertlast(int value)
tail = (tail + 1) % cap;
data[tail] = value;
return true;
}/** deletes an item from the front of deque. return true if the operation is successful. */
bool deletefront()
head = (head + 1) % cap;
return true;
}/** deletes an item from the rear of deque. return true if the operation is successful. */
bool deletelast()
tail = (tail - 1 + cap) % cap;
return true;
}/** get the front item from the deque. */
int getfront()
return data[head];
}/** get the last item from the deque. */
int getrear()
return data[tail];
}/** checks whether the circular deque is empty or not. */
bool isempty()
/** checks whether the circular deque is full or not. */
bool isfull()
}; // ac
/** * your mycirculardeque object will be instantiated and called as such:
* mycirculardeque* obj = new mycirculardeque(k);
* bool param_1 = obj->insertfront(value);
* bool param_2 = obj->insertlast(value);
* bool param_3 = obj->deletefront();
* bool param_4 = obj->deletelast();
* int param_5 = obj->getfront();
* int param_6 = obj->getrear();
* bool param_7 = obj->isempty();
* bool param_8 = obj->isfull();
*/// @lc code=end
c++ 中的 queue 的實現是什麼樣的?
c++ 中的 queue 和 stack 一樣,都並不是某一特定的型別,而是乙個「介面卡」。實際上,queue 的底層可以是乙個雙端佇列 deque,也可以是乙個雙鏈表,預設是deque。
deque 對記憶體的管理是以頁為單位分配陣列,頁內的元素在兩端的操作都可以像普通陣列一樣操作;頁與頁之間並不是連續分配,而是使用鍊錶或者索引表來管理,兩端的 push/pop 操作可能觸發頁分配和頁**。通過這種策略,**了空閒記憶體,也就是 「make use of the spaces in front of the queue」,當然 deque 也做到了 「make use of spaces in rear of the queue」。
緩衝區設計 環形佇列
目錄 在程式的兩個模組間進行通訊的時候,緩衝區成為乙個經常使用的機制。如上圖,寫入模組將資訊寫入緩衝區中,讀出模組將資訊讀出緩衝區。這樣使得 緩衝區顯然不適合下面的情況 佇列使用環形佇列,如上圖。環形佇列的特點是,不需要進行動態的記憶體釋放和分配,使用固定大小的記憶體空間反覆使用。在實際的佇列插入和...
緩衝環形佇列
在程式的兩個模組間進行通訊的時候,緩衝區成為乙個經常使用的機制。寫入模組將資訊寫入緩衝區中,讀出模組將資訊讀出緩衝區。這樣使得 緩衝區顯然不適合下面的情況 緩衝區的設計 佇列使用環形佇列,如上圖。環形佇列的特點是,不需要進行動態的記憶體釋放和分配,使用固定大小的記憶體空間反覆使用。在實際的佇列插入和...
c 環形佇列
上一章說到的陣列模擬佇列存在的問題,問題分析並優化 對前面的陣列模擬佇列的優化,充分利用陣列。因此將陣列看做是乙個環形的。通過去模的方式來實現即可 分析說明 實現思路如下 public class circlearrayqueue maxsize maxsize temparray new int ...