Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

stack in c#

/* Stack
 * Stack follows the LIFO last in First Out
 * It does not have a fixed size and increase according to the elements that have added to it.
 * We have stavk in both Syste.Collections nd System.Collections.Generic
 * But we recommended to use the generic Stack<T>
 * no boxing and unboxing fro generic stack but for the non generic stack you have to us the unvoxing methods 
 * Stack element can be added or deleted
 * heneric stack have specific data types elemnts
 */
//Create a stack
using System.Collections.Generic;
//Declaring a stack
Stack<int> s1 = new Stack<int>();
//Declare using var keyword
var s2  = new Stack<string>();
//Declare and initilze a stack simultaneousley
//You cant do that


//Adding elements to the stack :  Push() : Insert the item at the top of the stack
s1.Push(10);
s1.Push(20);
s1.Push(30);
//Here the stacj will be like this 30, 20, 10 : but the 30 added in the last 
s2.Push("Subhasis");
s2.Push("Aditi");

//Create a stack from an array
int[] a = new int[] { 4, 5, 6 };
Stack<int> s3 = new Stack<int>(a);

//Looping through stack
foreach(var item in s3)
    Console.WriteLine(item);
//Deleting from the stack :  Pop()
//The last element which is added to the  stack will be deleted when we use the pop method
s3.Pop();
foreach (var i in s3)
    Console.WriteLine($"The values after pop methods are : {i}");
/*The values after pop methods are : 5
The values after pop methods are : 4*/
s1.Pop();
foreach (var g in s1)
    Console.WriteLine($"The values in s1 after pop() : {g}");
/*The values in s1 after pop() : 20
The values in s1 after pop() : 10*/

//Take a peek at te last element : Peek() : Do not delete the last element just look at that value

Console.WriteLine(s1.Peek());
Console.WriteLine(s2.Peek());
Console.WriteLine(s3.Peek());
/*20
Aditi
5*/

//Count : give the numvber of elements in the stack
Console.WriteLine(s1.Count);
//Contains : check if the element is there or not
Console.WriteLine(s2.Contains("Aditi"));
/*2
True*/


Source by www.guru99.com #
 
PREVIOUS NEXT
Tagged: #stack
ADD COMMENT
Topic
Name
5+5 =