CS/자료구조 구현

구현 // 자료구조 // 스택(Stack) // toJava

문스코딩 2018. 8. 2. 13:00
public class MyStack {

/* Main */
public static void main(String[] args) {
Stack<Integer> stack = new Stack(16);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}

/* Stack */
public static class Stack<T> {

// == Field ==
public int capacity;
public int size;
public T[] bucket;

// == Constructor ==
public Stack(int capacity) {
this.capacity = capacity;
this.size = 0;
this.bucket = (T[]) new Object[capacity];
}

// == push ==
public void push(T t) {
if(size < capacity) {
this.bucket[size++] = t;
}
}

// == pop ==
public T pop() {
if(size > 0) {
return this.bucket[--size];
}
return null;
}

// == peek ==
public T peek() {
return this.bucket[size-1];
}

// == isEmpty ==
public boolean isEmpty() {
return size == 0 ? true : false;
}

// == size ==
public int size() {
return size;
}
}
}


반응형