반응형
백준 10828 스택
https://www.acmicpc.net/problem/10828
package 스택;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
static int N; //명령어의 수
static int[] stack = new int[10001];
static int cursor = 0;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
for(int i=0; i<N; i++){
String input = br.readLine();
String command = input.split(" ")[0];
if(command.equals("push")){
push(Integer.parseInt(input.split(" ")[1]));
}
if(command.equals("pop")){
System.out.println(pop());
}
if(command.equals("size")){
System.out.println(size());
}
if(command.equals("empty")){
if(isEmpty()) System.out.println("1");
else System.out.println("0");
}
if(command.equals("top")){
System.out.println( peek() );
}
}//for
}
static int size(){
return cursor;
}
static void push(int num){
stack[cursor++] = num;
}
static int pop(){
if(isEmpty()) return -1;
return stack[--cursor];
}
static int peek(){
if(isEmpty()) return -1;
return stack[cursor-1];
}
static boolean isEmpty(){
if(cursor==0) return true;
return false;
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//N개의 정수를 배열로 받음
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt( st.nextToken() );
MyStack stack = new MyStack();
for(int i=0; i<N; i++) {
stack.setCommand( new StringTokenizer(br.readLine()) );
}
}
public static class MyStack{
int top=0;
int[] arr = new int[10001];
public void setCommand(StringTokenizer st) {
String command = st.nextToken();
if(command.equals("push")) {
push(Integer.parseInt(st.nextToken()));
}else if(command.equals("pop")) {
System.out.println(pop());
}else if(command.equals("size")) {
System.out.println(size());
}else if(command.equals("empty")){
System.out.println(empty());
}else if(command.equals("top")) {
System.out.println(top());
}
}
public void push(int num){
arr[top++] = num;
}
public int pop() {
if(top==0) return -1;
return arr[--top];
}
public int size() {
return top;
}
public int empty() {
if(top==0) return 1;
return 0;
}
public int top() {
if(top==0) return -1;
return arr[top-1];
}
}
}
반응형
'자료구조 구현' 카테고리의 다른 글
병합정렬 (0) | 2019.05.07 |
---|---|
백트래킹 구현 (0) | 2019.04.03 |
[Heap] Priority Queue(우선순위 큐) (0) | 2019.03.21 |
Quick Sort(퀵정렬) (0) | 2019.03.21 |
Hash(해쉬) (0) | 2019.03.05 |