Saturday, May 30, 2009

C♯ or Implement That Stack

A friend of mine reminded me of the importance to implement the stack ADT for the sake of learning a new programming language. CS really feels strange to me, so I implemented the stack. To test the program, I implemented a small postfix-notation parser -- like 1 1 + 2 * = 4, too.
using System;
using System.Collections;

public class Stack 
{
  ArrayList xs;
  
  public Stack()
  {
    xs = null;
  }
  
  bool empty()
  {
    return (xs == null);
  }

  void push(int x)
  {
    if (empty() == true) {
      xs = new ArrayList();
    }
    xs.Add(x);
    Console.WriteLine("PUSH " + x);
  }
  
  int pop()
  {
    Console.WriteLine("POP " + (int) xs[xs.Count - 1]);
    return (int) xs[xs.Count - 1];
  }

  private static int ctoi(char c)
  {
    return int.Parse(c.ToString());
  }

  private static bool number(char c)
  {
    try {
      ctoi(c);
      return true;
    } catch (FormatException f) {
      return false;
    }
  }

  public static void Main(string[] args)
  {
    string cs = args[0];
    Stack s = new Stack();

    for (int i = 0; i < cs.Length; i++) {
      switch (cs[i]) {
      case '+':
        s.push(s.pop() + s.pop());
        break;
      case '*':
        s.push(s.pop() * s.pop());
        break;
      case ' ':
        break;
      default:
        s.push(ctoi(cs[i]));
        i++;
        while (number(cs[i])) {
          s.push(10 * s.pop() + ctoi(cs[i]));
          i++;
        }
        break;
      }
    }
    Console.WriteLine(s.pop());
  }
}

No comments: