
package Interface_form;
public interface StackInterface<E> {
/**
* 스택의 제일 위에 요소룰 추가
* @param item 추가할 요소
* @return 추가된 요소
*/
E push(E item);
/**
* 스택의 제일 위에 있는 요소를 제거하고 반환
* @return 제거된 요소
*/
E pop();
/**
* 스택의 제일 위에 있는 요소를 제거하지 않고 반환
* @return 제일 윗 요소
*/
E peek();
/**
* 스택의 제일 위부터 특정 요소가 몇 번째 위치에 있는지 반환
* 중복되는 요소가 있는 경우 처음으로 찾은 요소의 위치가 반환
*
* @param value 스택에서 위치를 찾을 요소
* @return 찾은 요소가 상단에서부터 얼마나 떨어져있는지 반환,
* 일치하는 요소가 없으면 -1 반환
*/
int search(Object value);
/**
* 스택의 요소 개수 반환
* @return 요소 개수
*/
int size();
/**
* 스택 clear
*/
void clear();
/**
* 스택이 비어있는지 반환
* @return 스택에 요소가 없는 경우 true, 요소가 있다면 false
*/
boolean empty();
}
import java.util.Arrays;
import java.util.EmptyStackException;
import Interface_form.StackInterface;
public class Stack<E> implements StackInterface<E> {
private static final int DEFAULT_CAPACITY = 10;
private static final Object[] EMPTY_ARRAY = {};
private int size;
private Object[] array;
public Stack() {
this.array = EMPTY_ARRAY;
this.size = 0;
}
public Stack(int capacity) {
this.array = new Object[capacity];
this.size = 0;
}
private void resize() {
if(Arrays.equals(EMPTY_ARRAY, array)) {
this.array = new Object[DEFAULT_CAPACITY];
return;
}
int arrayCapacity = array.length;
if(size == arrayCapacity) {
int newsize = arrayCapacity*2;
array = Arrays.copyOf(array, newsize);
return;
}
if(size< (arrayCapacity/2)) {
int newsize = arrayCapacity/2;
array = Arrays.copyOf(array, Math.max(DEFAULT_CAPACITY, newsize));
return;
}
}
public E push(E data) {
if(size == array.length) {
resize();
}
array[size] = data;
size++;
return data;
}
@Override
@SuppressWarnings("unchecked")
public E pop() {
if(size == 0) {
throw new EmptyStackException();
}
E element = (E) array[size-1];
array[size-1] = null;
size--;
resize();
return element;
}
@Override
@SuppressWarnings("unchecked")
public E peek() {
if(size == 0) {
throw new EmptyStackException();
}
return (E) array[size-1];
}
@Override
public int search(Object data) {
for(int index = size-1; index>=0; index--) {
if(array[index].equals(data)) {
return size - index;
}
}
return -1;
}
@Override
public int size() {
return this.size;
}
@Override
public void clear() {
for(int i=0; i<size; i++) {
array[i] = null;
}
size=0;
resize();
}
@Override
public boolean empty() {
return size==0;
}
}
https://st-lab.tistory.com/161?category=856997
내가 직접 코딩해보고 사이트를 확인하여 수정하는 방법으로 구현을 진행했음