Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
A specialization of Stack


Here is my version of the non-abstract specialization of the abstract class Stack:

using System;

public class StackWithArray: Stack{ 

  private Object[] elements;
  private int nextPush;
  private int MaxSize; 

  public StackWithArray(int MaxSize){
    elements = new Object[MaxSize];
    nextPush = 0;
    this.MaxSize = MaxSize;
  }
  
   public override void Push(Object el){
     if (!Full){
       elements[nextPush] = el;
       nextPush++;
    }
  }

   public override void Pop(){
   if (!Empty)
     nextPush--;
   }

   public override Object Top{
    get{
      if (!Empty)
         return elements[nextPush-1];
      else return "not possible";}
   }

   public override bool Full{
    get{return nextPush >= MaxSize;}
   }

   public override bool Empty{
    get{return nextPush == 0;}
   }

   public override int Size{
    get{return nextPush;}
   }   

  public override String ToString(){
    string res = "Stack: ";
    for(int i = 0; i < nextPush; i++){
      res += elements[i] + " ";}
    return res;
  }

}

Here follows a sample client program:

using System;

class C{

  public static void Main(){

    Stack s = new StackWithArray(10);

    Console.WriteLine("Empty: {0}", s.Empty);
    Console.WriteLine("Full: {0}", s.Full);

    s.Push(5); s.Push(6);  s.Push(7);      
    s.Push(15); s.Push(16);  s.Push(17); 
    s.Push(18); s.Push(19);  s.Push(20); 
    s.Push(21); 

    Console.WriteLine("{0}", s.Size);
    Console.WriteLine("{0}", s.Top);
    Console.WriteLine("{0}", s);

    s.Pop();s.Pop();s.Pop();s.Pop();s.Pop();s.Pop();s.Pop();

    Console.WriteLine("Empty: {0}", s.Empty);
    Console.WriteLine("Full: {0}", s.Full);
    Console.WriteLine("Top: {0}", s.Top);

    Console.WriteLine("{0}", s);
    s.ToggleTop();
    Console.WriteLine("{0}", s);

  }

}