2014년 2월 5일 수요일

자바 배열로 구현한 스택(java array stack) 소스,JAVA자료구조,자바강좌교육, 구로디지털단지자바교육학원,GURO JAVA교육센터


자바 배열로 구현한 스택(java array stack) 소스,JAVA자료구조,자바강좌교육, 구로디지털단지자바교육학원,GURO JAVA교육센터
 
 
 
interface Stack {  
            public boolean isEmpty();
            public Object peek();
            public void push(Object theObject);
            public Object pop();
}
 
 
 
 public class ArrayStack implements Stack   {           
             int top;         // current top of stack
             Object [] stack;   // element array
              
             public ArrayStack(int initialCapacity) {
                  if (initialCapacity < 1)
                  throw new IllegalArgumentException
                                        ("initialCapacity must be >= 1");
                  stack = new Object [initialCapacity] ;
                  top = -1;
             }
     
       public ArrayStack() {
      this(10);
       }
      
       public boolean isEmpty( ) {
          return top == -1;
       }      
       
        public Object peek() {
               if (isEmpty() )
                     throw new EmptyStackException();
               return stack[top];
        }    

       
  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;
      }

 
     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());
  }
}
 

댓글 없음:

댓글 쓰기