Home   Cover Cover Cover Cover
 

Vererbung

A02.cs
using System;

//==========================================================
// Stack< T >
//==========================================================
class Stack< T > {
  protected T[] data;
  protected int top;
  
  // creates stack of the specified size
  public Stack(int size) {
    data = new T[size];
    top = -1;
  }
  
  // pushes the value x on the stack
  public void Push(T x) {
    if (top == data.Length - 1) throw new Exception("-- stack overflow");
    data[++top] = x;
  }
  
  // pops the topmost value from the stack
  public T Pop() {
    if (top < 0) throw new Exception("-- stack underflow");
    return data[top--];
  }
  
  // returns the stack size
  public int Size {
    get { return top + 1; }
  }
}

//==========================================================
// BetterStack< T >
//==========================================================
class BetterStack< T > : Stack< T > {
  
  // creates stack of the specified size
  public BetterStack(int size): base(size) {}
  
  // returns true if x is on the stack
  public bool Contains(T x) {
    for (int i = 0; i <= top; i++)
      if (x.Equals(data[i])) return true;
    return false;
  }
  
  // returns the i-th element of the stack
  public T this[int i] {
    get {
      if (i < 0 || i > top) throw new Exception("-- index out of bounds");
      return data[i];
    }
  }
}

//----------------------------------------------------------
// test program; to be called with a list of argument words
//----------------------------------------------------------
class Test {
  
  public static void Main(string[] args) {
    BetterStack<string> stack = new BetterStack<string>(10);
    foreach (string s in args) stack.Push(s);
    
    for (int i = 0; i < stack.Size; i++)
      Console.WriteLine(stack[i]);
    Console.WriteLine();
    
    for(;;) {
      Console.Write("> ");
      string word = Console.ReadLine();
      if (word.Length == 0) break;
      if (stack.Contains(word))
        Console.WriteLine("  found");
      else
        Console.WriteLine("  not found");
    }
  }
}