스택은 후입선출(Last In Frist Out)인 자료구조형이다.
자바에서 제공하고 있는 스택 클래스는 Vector클래스를 상속받고 있으며, 메소드는 Vetor클래스와 동일하다.
Vector클래스는 list인터페이스를 구현하였기 때문에 다음 문제는 ArrayList로 list를 생성하고 스택에서 사용되는 함수를 처리하는 프로그램을 작성하였다.
들어오는 입력값을 if문을 통하여서 다음 다섯가지 명령으로 처리하였다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
List<String> list = new ArrayList<String>();
int index = 0;
for(int i = 0 ; i < N; i++){
StringTokenizer st = new StringTokenizer(br.readLine());
String str = st.nextToken();
if(str.equals("push")){
list.add(st.nextToken());
index++;
}
else if(str.equals("pop")){
if(list.isEmpty()){
System.out.println("-1");
}
else{
System.out.println(list.get(index-1));
list.remove(index-1);
index--;
}
}
else if(str.equals("size")){
System.out.println(list.size());
}
else if(str.equals("empty")){
if(list.isEmpty()){
System.out.println("1");
}
else{
System.out.println("0");
}
}
else if(str.equals("top")){
if(list.isEmpty()){
System.out.println("-1");
}
else{
System.out.println(list.get(index-1));
}
}
}
}
}