星期六, 5月 28, 2011

c++ code: Stack

引用自http://www.cs.utsa.edu/~wagner/CS2213/stack/stack.html

好漂亮的程式碼!



// stack.h: header file
class Stack {
   int MaxStack;
   int EmptyStack;
   int top;
   char* items;
public:
   Stack(int);
   ~Stack();
   void push(char);
   char pop();
   int empty();
   int full();
};
-------------------------------
// stack.cpp: stack functions
#include "stack.h"

Stack::Stack(int size) {
   MaxStack = size;
   EmptyStack = -1;
   top = EmptyStack;
   items = new char[MaxStack];
}

Stack::~Stack() {delete[] items;}

void Stack::push(char c) {
   items[++top] = c;
}

char Stack::pop() {
   return items[top--];
}

int Stack::full()  {
   return top + 1 == MaxStack;
}

int Stack::empty()  {
   return top == EmptyStack;
}

-------------------------------
// stackmain.cpp: use stack
#include 
#include "stack.h"

int main() {

   Stack s(10); // 10 chars
   char ch;
   while ((ch = cin.get()) 
         != '\n')
      if (!s.full()) s.push(ch);
   while (!s.empty())
      cout << s.pop();
   cout << endl;
   return 0;
}

沒有留言:

張貼留言