백준 10828 - 스택 (자바)

남현·2025년 1월 19일

백준

목록 보기
1/16

문제

풀이1

import java.util.Scanner;
import java.util.Stack;
class Main {
	public static void main(String[] args) {
    	Scanner sc = new Scanner(System.in);
    	Stack<Integer> st = new Stack<>();
    	int N = sc.nextInt();
    	for(int i=0; i<N; i++) {
    		String a = sc.next();
    		switch(a) {
    		case "push":
    			int x = sc.nextInt();
    			st.push(x);
    			break;
    		case "pop":
    			if(!st.isEmpty()) {
    				System.out.println(st.pop());
    			} else {
    				System.out.println(-1);
    			}
    			break;
    		case "size":
    			System.out.println(st.size());
    			break;
    		case "empty":
    			if(st.isEmpty()) {
    				System.out.println(1);
    			} else {
    				System.out.println(0);
    			}
    			 break;
    		case "top":
    			if(!st.isEmpty()) {
    				System.out.println(st.peek());
    			} else {
    				System.out.println(-1);
    			}
    			break;
    		}
    	}
    	sc.close();
    }
}

자바의 스택을 사용해서 문제를 풀었다. 명령의 수를 입력받고 switch case문으로 입력받은 명령에 따라 스택의 기능을 수행한다.

push() : 데이터를 스택에 추가하고 해당 값을 반환

pop() : 스택의 마지막 요소(가장 위에 있는 값)를 제거함과 동시에 해당 값을 반환

isEmpty() : empty()와 같은 기능 스택이 비어있는지 아닌지를 판단 비어있으면 true 비어있지 않으면 false 반환

peek() : 스택의 마지막 요소(가장 위에 있는 값) 반환. 스택에는 변화를 주지 않음

size() : 스택의 크기를 반환

풀이2


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		NumStk stk = new NumStk(N);
		for(int i=0; i<N; i++) {
			String cmd = sc.next();
			
			switch(cmd) {
			case "push":
				int num = sc.nextInt();
				stk.push(num);
				break;
			case "top":
				stk.top();
				break;
			case "size":
				stk.size();
				break;
			case "empty":
				stk.empty();
				break;
			case "pop":
				stk.pop();
				break;
			}
		}
		sc.close();
	}
}

class NumStk {
	private int[] n;
	private int top;
	
	public NumStk(int p) {
		n = new int[p];
		top = -1;
	}
	public void push(int p) {
		n[++top] = p;
	}
	public void top() {
		if(top == -1) {
			System.out.println(top);
		} else {
			System.out.println(n[top]);
		}
	}
	public void size() {
		System.out.println(top + 1);
	}
	public void empty() {
		if (top == -1) {
			System.out.println(1);
		} else {
			System.out.println(0);
		}
	}
	public void pop() {
		if(top != -1) {
			System.out.println(n[top--]);
		} else {
			System.out.println(top);
		}
	}
}

스택의 역할을 하는 클래스를 구현해서 문제를 해결하였다.

profile
백엔드 호소인

0개의 댓글