I implemented a generic stack class and the code goes like this:
public class Stack
{
///
/// Top of the Stack
///
private int top;
///
/// Generic Collection to hold stack contents
///
private System.Collections.Generic.Collection
///
/// Stack Constructor
///
///
public Stack(System.Collections.Generic.Collection
{
data = t;
top = 0;
}
///
/// Default Constructor
///
public Stack()
{
data = new System.Collections.Generic.Collection
top = 0;
}
///
/// Push
///
/// Item/Content to be pushed
public void push(T item)
{
data.Insert(top,item);
top++;
}
///
/// POP
///
///
public T pop()
{
if (top > 0)
{
top = top - 1;
return data[top];
}
else
{
throw new IndexOutOfRangeException(" Stack is already empty");
}
}
}
#endregion
#region Testing Stack Class
///
/// Testing Stack Class
///
class Program
{
static void Main(string[] args)
{
// Stack Class Object -- See char as type paramter..
//(this reminds me of C++ :))
Stack
myStack.push('H');
myStack.push('A');
myStack.push('M');
Console.WriteLine(myStack.pop().ToString());
Console.WriteLine(myStack.pop().ToString());
Console.WriteLine(myStack.pop().ToString());
// Index Out of Bound Exception
Console.WriteLine(myStack.pop().ToString());
Console.ReadLine();
}
}
#endregion
}
This code wont get me any accoldate, that I know :). But it still proves the point that Generics are simple and very useful in terms of re-usable data structures.
No comments:
Post a Comment