Generic Stack based on generic Array
using System;
using System.Collections.Generic;
class MyStack<T> {
int MaxStack = 10;
T[] StackArray;
int StackPointer = 0;
public MyStack() {
StackArray = new T[MaxStack];
}
public void Push(T x) {
if (StackPointer < MaxStack)
StackArray[StackPointer++] = x;
}
public T Pop() {
return (StackPointer > 0)
? StackArray[--StackPointer]
: StackArray[0];
}
public void Print()
{
for (int i = StackPointer - 1; i >= 0; i--)
Console.WriteLine(" Value: {0}", StackArray[i]);
}
}
class MainClass
{
static void Main()
{
MyStack<int> StackInt = new MyStack<int>();
MyStack<string> StackString = new MyStack<string>();
StackInt.Push(3);
StackInt.Push(7);
StackInt.Print();
StackString.Push("This is fun");
StackString.Push("Hi there! ");
StackString.Print();
}
}
Value: 7
Value: 3
Value: Hi there!
Value: This is fun
Push and pop value in a generic Stack<T>
using System;
using System.Collections.Generic;
class MainClass {
public static void Main() {
Stack<string> st = new Stack<string>();
st.Push("One");
st.Push("Two");
st.Push("Three");
st.Push("Four");
st.Push("Five");
while(st.Count > 0) {
string str = st.Pop();
Console.Write(str + " ");
}
Console.WriteLine();
}
}
Five Four Three Two One
Use generic Statck to store your own class
using System;
using System.Collections.Generic;
class MainClass
{
public static void Main(string[] args)
{
// Create and use a Stack of Assembly Name objects
Stack<MyClass> stack = new Stack<MyClass>();
stack.Push(new MyClass());
MyClass ass3 = stack.Pop();
Console.WriteLine("\nPopped from stack: {0}", ass3);
}
}
class MyClass {
public override string ToString(){
return "my class";
}
}
Popped from stack: my class