c# collection part-2 (Stack)
What is Stack in C#?
The stack is a special case collection which represents a last in first out (LIFO) concept. To first understand LIFO, example : a stack of books with each book kept on top of each other.
Declaration of the stack
A stack is created with the help of the Stack Datatype. The keyword "new" is used to create an object of a Stack. The object is then assigned to the variable st.
Stack st = new Stack();
Adding elements to the stack
The push method is used to add an element to the stack. The general syntax of the statement is given below.
st.push(Element);
Removing elements from the stack
The pop method is used to remove an element from the stack. The pop operation will return the topmost element of the stack. The general syntax of the statement is given below
st.pop();
Contains
This method is used to see if an element is present in the Stack. Below is the general syntax of this statement. The statement will return true if the element exists, else it will return the value false.
st.Contains(element);
Example:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoApplication
{
class Program
{
static void Main(string[] args)
{
Stack st = new Stack();
st.Push(1);
st.Push(2);
st.Push(3);
foreach (Object obj in st)
{
Console.WriteLine(obj);
}
Console.WriteLine(); Console.WriteLine();
Console.WriteLine("The number of elements in the stack " +st.Count);
Console.WriteLine("Does the stack contain the elements 3 "+st.Contains(3));
Console.ReadKey();
}
}
}
Example 2:using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoApplication
{
class Program
{
static void Main(string[] args)
{
Stack st = new Stack();
st.Push(1);
st.Push(2);
st.Push(3);
st.Pop();
foreach (Object obj in st)
{
Console.WriteLine(obj);
}
Console.ReadKey();
}
}
}
Comments
Post a Comment