'Push'에 해당되는 글 1건

  1. 2007/08/27 Stack Tutorial In C#
2007/08/27 08:32

Stack Tutorial In C#

stack is aLIFO (Last In First Out) queue, so if you add two items and then ask for an item you would get the second item then the first item. To add items to theStack you usePush method. This method takes an object of any type but to keep things simple lets just give it a string object:

Stack s = new Stack();

s.Push("So");
s.Push("This");
s.Push("Is");
s.Push("How");
s.Push("Queues");
s.Push("Work");


 

Viewing a Single Object Without Removing it From the Stack
You can use the Peak method to get the bottom-most object in the Stack without removing it from the Stack:

Console.WriteLine(s.Peek());


 

Viewing All the Objects in the Stack Without Removing Them
You can read any of the data in the Stack by using an enumerator:

System.Collections.IEnumerator en = s.GetEnumerator();

while (en.MoveNext())
{
   Console.Write(en.Current   " ");
}


 

Removing Items from the Stack
To pop an item from the Stack you can use thePop statement. This returns the bottom-most object of the stack.

while( s.Count > 0)
{
   Console.Write(s.Pop()   " ");
}

Trackback 0 Comment 0