Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace Generics {
- class Program {
- static void Main(string[] args) {
- MyStack<int> stack = new MyStack<int>();
- Random rand = new Random();
- for (int i = 0; i < 5; i++)
- stack.EnQueue(rand.Next(1000));
- for(int i = 1; i <= stack.length; i++)
- Console.WriteLine(i + ": " + stack.At(i - 1));
- Console.WriteLine("Popping");
- for(int i = stack.length; i > 0; i--)
- Console.WriteLine(stack.DeQueue());
- Console.ReadKey(true);
- }
- }
- class ElementInStack<T> {
- public ElementInStack(T value){
- this.value = value;
- }
- public T value;
- public ElementInStack<T> next;
- public T At(int index) {
- if (index == 0)
- return value;
- if (next == null)
- throw new Exception("Index out of range");
- return next.At(index - 1);
- }
- }
- class MyStack<T> {
- ElementInStack<T> first;
- ElementInStack<T> last;
- public int length { get; private set; }
- public MyStack() {
- length = 0;
- }
- public void EnQueue(T value) {
- ElementInStack<T> element = new ElementInStack<T>(value);
- length++;
- if (first == null) {
- first = element;
- last = first;
- }
- else {
- last.next = element;
- last = element;
- }
- }
- public T DeQueue() {
- if(first == null)
- throw new Exception("Stack empty");
- else {
- length--;
- T temp = first.value;
- first = first.next;
- return temp;
- }
- }
- public T At(int index) {
- return first.At(index);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement