您的位置首页生活百科

堆栈是什么意思

堆栈是什么意思

Stack) 类

表示同一任意类型的实例的大小可变的后进先出 (LIFO) 集合。

只要理解后进先出,那他的概念就大概的理解了

比如,我将以下数字顺序入栈

1,2,3

出栈(POP)顺序就是3,2,1

很好记

下面是一个例子

另外,注意下,其实平时说的堆栈,指的就是堆

堆和栈是两种不同的数据结构

using System;

using System.Collections.Generic;

class Example

{

public static void Demo(System.Windows.Controls.TextBlock outputBlock)

{

Stack numbers = new Stack();

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)

{

outputBlock.Text += number + "\n";

}

outputBlock.Text += String.Format("\nPopping '{0}'", numbers.Pop()) + "\n";

outputBlock.Text += String.Format("Peek at next item to destack: {0}",

numbers.Peek()) + "\n";

outputBlock.Text += String.Format("Popping '{0}'", numbers.Pop()) + "\n";

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

// constructor that accepts an IEnumerable.

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

outputBlock.Text += "\nContents of the first copy:" + "\n";

foreach (string number in stack2)

{

outputBlock.Text += number + "\n";

}

// 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);

outputBlock.Text += String.Format("\nContents of the second copy, with duplicates and nulls:") + "\n";

foreach (string number in stack3)

{

outputBlock.Text += number + "\n";

}

outputBlock.Text += String.Format("\nstack2.Contains(\"four\") = {0}",

stack2.Contains("four")) + "\n";

outputBlock.Text += "\nstack2.Clear()" + "\n";

stack2.Clear();

outputBlock.Text += String.Format("\nstack2.Count = {0}", stack2.Count) + "\n";

}

}

抖音看短剧