FullStack/21. Java
[알고리즘] Stack
by nakanara
2014. 3. 24.
FILO(First In Last Out) 구조인 스택 구현.
package com.nakanara.stack;
/** * Stack. * @author nakanara * */ public class Stack {
private static final int MAX_SIZE = 5; // 스택 크기 private int data[] = new int[Stack.MAX_SIZE]; // 자료 저장 private int position = 0; // 스택 위치 /** * 데이터 입력. * @param val * @throws Exception */ public void push(int val) throws Exception { if(position == (Stack.MAX_SIZE-1)) { throw new Exception("스택 overflow"); } data[position++] = val; } /** * 데이터 출력 * @return * @throws Exception */ public int pop() throws Exception { if(position == 0) { throw new Exception("스택이 비어있음."); } return data[--position]; } public String toString(){ StringBuffer buffer = new StringBuffer(); int i=0; for(int v : data) { buffer.append(i++).append(":").append(v).append("|"); } return buffer.toString(); } public static void main(String args[]) { Stack stack = new Stack(); try { stack.push(1); stack.push(2); System.out.println("get=" + stack.pop()); System.out.println("get=" + stack.pop()); stack.push(3); stack.push(4); stack.push(5); stack.push(6); stack.push(7); stack.push(8); System.out.println(stack.toString()); }catch (Exception e) { System.out.println(e.getMessage()); } } } |