C#中Stack 類的使用及部分成員函數的源代碼分析


Stack<T>類

Stack<T> 作為數組來實現。

Stack<T> 的容量是 Stack<T> 能夠包括的元素數。

當向 Stack<T> 中加入元素時,將通過又一次分配內部數組來依據須要自己主動增大容量。

可通過調用 TrimExcess 來降低容量。 假設 Count 小於堆棧的容量,則 Push 的運算復雜度是 O(1)。 假設須要添加容量以容納新元素,則 Push 的運算復雜度成為 O(n)。當中 n 為 Count。 Pop 的運算復雜度為 O(1)。

Stack<T> 接受 null 作為引用類型的有效值而且同意有反復的元素。

命名控件:System.Collections.Generic

程序集:System(在System.dll中)

語法:public class Stack<T>:IEnumerable<T>, ICollection, IEnumerable

List<T>實現了IList<T>、 ICollection<T>、IEnumerable<T>、IList、ICollection、IEnumerable接口

因此能夠看出與List1T>相比:

Stack<T>沒有繼承ICollection<T>接口,由於這個接口定義的Add()和Remove()方法不能用於棧;

Stack<T>沒有繼承IList<T>接口,所以不能使用索引器訪問棧。

所以隊列僅僅同意在棧的頂部加入元素,刪除元素。

經常使用的Stack<T>類的成員:

Count : 返回棧中元素的個數。

Push(): 在棧頂加入一個元素。

Pop() : 從棧頂刪除一個元素。

假設棧是空,就會拋出異常InvalidOperationException異常。

Peek(): 返回棧頂的元素,但不刪除它。

Contains(): 確定某個元素是否在棧中。假設是,返回true。

/******************************************************************************************************************************/

經常使用Stack1T>類的成員函數的源代碼例如以下:

public bool Contains(T item)

{

int index = this._size;

EqualityComparer<T> comparer = EqualityComparer<T>.Default;

while (index-- > 0)

{

if (item == null)

{

if (this._array[index] == null)

{

return true;

}

}

else if ((this._array[index] != null) && comparer.Equals(this._array[index], item))

{

return true;

}

}

return false;

}

public T Peek()

{

if (this._size == 0)

{

ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EmptyStack);

}

return this._array[this._size - 1];

}

public T Pop()

{

if (this._size == 0)

{

ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EmptyStack);

}

this._version++;

T local = this._array[--this._size];

this._array[this._size] = default(T);

return local;

}

public void Push(T item)

{

if (this._size == this._array.Length)

{

T[] destinationArray = new T[(this._array.Length == 0) ? 4 : (2 * this._array.Length)];

Array.Copy(this._array, 0, destinationArray, 0, this._size);

this._array = destinationArray;

}

this._array[this._size++] = item;

this._version++;

}

/*****************************************************************************************************************************************/

以下的代碼演示樣例演示了 Stack 泛型類的幾種方法。 此代碼演示樣例創建具有默認容量的字符串堆棧,並使用 Push 方法將五個字符串壓入堆棧。

枚舉堆棧的元素,這不會更改該堆棧的狀態。

使用 Pop 方法將第一個字符串彈出堆棧。 使用 Peek 方法查看此堆棧中的下一個項,然后使用 Pop 方法將其彈出。

使用 ToArray 方法創建數組並將堆棧元素拷貝到當中,然后將數組傳遞給具有 IEnumerable 的 Stack 構造函數,以元素的反向順序創建堆棧副本。

將顯示副本的元素。

創建大小為堆棧大小兩倍的數組,並使用 CopyTo 方法從數組的中間開始復制數組元素。

再次使用 Stack 構造函數以元素的反向順序創建堆棧副本;這樣。三個空元素就位於堆棧的底部。

使用 Contains 方法顯示字符串“four”在第一個堆棧副本中。然后使用 Clear 方法清除該副本,並由 Count 屬性顯示此堆棧為空。

using System;

using System.Collections.Generic;

class Example

{

public static void Main()

{

Stack<string> numbers = new Stack<string>();

numbers.Push("one");

numbers.Push("two");

numbers.Push("three");

numbers.Push("four");

numbers.Push("five");

// A stack can be enumerated without disturbing its contents.

foreach( string number in numbers )

{

Console.WriteLine(number);

}

Console.WriteLine("\nPopping '{0}'", numbers.Pop());

Console.WriteLine("Peek at next item to destack: {0}", numbers.Peek());

Console.WriteLine("Popping '{0}'", numbers.Pop());

// Create a copy of the stack, using the ToArray method and the

// constructor that accepts an IEnumerable.

Stack stack2 = new Stack(numbers.ToArray());

Console.WriteLine("\nContents of the first copy:");

foreach( string number in stack2 )

{

Console.WriteLine(number);

}

// Create an array twice the size of the stack and copy the

// elements of the stack, starting at the middle of the

// array.

string[] array2 = new string[numbers.Count * 2];

numbers.CopyTo(array2, numbers.Count);

// Create a second stack, using the constructor that accepts an

// IEnumerable(Of T).

Stack stack3 = new Stack(array2);

Console.WriteLine("\nContents of the second copy, with duplicates and nulls:");

foreach( string number in stack3 )

{

Console.WriteLine(number);

}

Console.WriteLine("\nstack2.Contains(\"four\") = {0}",stack2.Contains("four"));

Console.WriteLine("\nstack2.Clear()");

stack2.Clear();

Console.WriteLine("\nstack2.Count = {0}", stack2.Count);

}

}

/* This code example produces the following output:

five

four

three

two

one

Popping 'five'

Peek at next item to destack: four

Popping 'four'

Contents of the first copy:

one

two

three

Contents of the second copy, with duplicates and nulls:

one

two

three

stack2.Contains("four") = False

stack2.Clear()

stack2.Count = 0

*/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM