2013년 8월 13일 화요일

자바 배열로 구현한 스택 (Java Array Stack)

오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(신입사원채용무료교육, 오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷)  



public class ArrayStack implements Stack  {           
            int top;        // current top of stack
            Object [] stack;  // element array

            /* create a stack with the given initial capacity  */ 
            public ArrayStack(int initialCapacity) {
                  if (initialCapacity < 1)
                  throw new IllegalArgumentException
                                        ("initialCapacity must be >= 1");
                  stack = new Object [initialCapacity] ; 
                  top = -1; 
            }

  /** create a stack with initial capacity 10  **/ 
      public ArrayStack() { 
    this(10); 
      }
      /** return true if stack is empty  */ 
      public boolean isEmpty( ) { 
          return top == -1; 
      }       
        /** return top element of stack
          * throw EmptyStackException when the stack is empty */
        public Object peek() {
              if (isEmpty() ) 
                    throw new EmptyStackException();
              return stack[top];
        }     


/** add theElement to the top of the stack    */       
  public void push(Object theElement) {
  // increase array size if necessary   
  if (top == stack.length - 1) ensureCapacity();
         
            // put theElement at the top of the stack 
            stack[++top] = theElement; 
      }


/** remove top element of stack and return it
  * throw EmptyStackException when the stack is empty */ 
    public Object pop() {
            if  (isEmpty())
                  throw new EmptyStackException();
            Object topElement = stack[top];
            stack[top--] = null;  // enable garbage collection
            return topElement;
      }   

  private void ensureCapacity()  {
      Object[] larger = new Object[stack.length*2];

      for (int index=0; index < stack.length; index++)
        larger[index] = stack[index];

      stack = larger;
  }

  public String toString() {
    if (isEmpty())
      return "<empty stack>";
    String result = "<stack :";
    for (int i = top; i >= 0; i--)
      result += stack[i] + " ";
    return result + ">";
  } // end toString
}




public class EmptyStackException extends RuntimeException {
  public EmptyStackException()  {
      super ("The stack is empty.");
  }

  public EmptyStackException (String message)  {
      super (message);
  }
}



public class Main {
  public static void main(String args[]) {   
      Stack myStack = new ArrayStack();
      myStack.push("a");
      myStack.push("b");
      myStack.push("c");
  System.out.println(myStack);
  myStack.pop();   
    System.out.println(myStack);   
  System.out.print("현재 top pointer의 data : ");
    System.out.println(myStack.peek());
  }

댓글 없음:

댓글 쓰기