我發現不止一次,泛型集合需要在某個時間點被視爲列表,在另一個時間點被視爲棧或隊列。對於我正在開發的應用程序,使用三個單獨的對象是沒有意義的。實現自定義通用列表/隊列/堆棧組合的有效方式
我能想到的最簡單的解決方案是在標準列表上實現隊列/出隊/推/流行/窺視功能。另外(不包括在下面的代碼中),在T上應用接口約束,允許類爲每個列表,隊列和堆棧維護位置/序號索引。
public class List<T>:
System.Collections.Generic.List<T>
{
private object SyncRoot = new object();
public void Enqueue (T item)
{
lock (this.SyncRoot)
{
this.Add(item);
}
}
public T Dequeue()
{
T item = default(T);
lock (this.SyncRoot)
{
if (this.Count > 0)
{
item = this [0];
this.RemoveAt(0);
}
}
return (item);
}
public void Push (T item)
{
lock (this.SyncRoot)
{
this.Add(item);
}
}
public T Pop()
{
T item = default(T);
lock (this.SyncRoot)
{
if (this.Count > 0)
{
item = this [this.Count - 1];
this.RemoveAt(this.Count - 1);
}
}
return (item);
}
public T PeekQueue()
{
T item = default(T);
lock (this.SyncRoot)
{
if (this.Count > 0)
{
item = this [0];
}
}
return (item);
}
public T PeekStack()
{
T item = default(T);
lock (this.SyncRoot)
{
if (this.Count > 0)
{
item = this [this.Count - 1];
}
}
return (item);
}
}
- 由於這是一個粗略的,在即時實現,我不知道要尋找什麼角落的情況下出了那麼將不勝感激指針或鏈接到任何現有的這樣的實現。其次,我對非常大的名單上的表現持懷疑態度。是否決定從列表繼承,而不是使用說LinkedList的大列表。在我的情況下,添加/刪除項目的優先級高於枚舉列表。
注:我也知道這樣一類不會讓供其他開發人員使用的一個很好的候選人,因爲相結合的列表,隊列和棧的功能可以說是相當反直覺取決於你如何使用它們。 –
http://weblogs.asp.net/bsimser/archive/2011/01/13/generic-pop-and-push-for-list-lt-t-gt。aspx – hagensoft
@hagensoft:我似乎無法訪問頁面內容。它只能部分加載。你可以在這裏粘貼要點嗎? –