백준 10828 - 스택 (자바)

남현·2025년 7월 23일

백준

목록 보기
5/16

문제

최근에 다시 문제를 풀어보았다.

풀이1

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

회고

.equals()를 사용하지 않고 == 비교를 하여 컴파일 에러가 발생 -> == 비교는 문자열의 내용이 아닌 참조(주소)를 비교하기 때문에 .equlas()를 사용해야 문자열 내용 비교를 정확하게 가능

풀이2

import java.util.*;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		St st = new St(N);
		for(int i=0; i<N; i++) {
			String str = sc.next();
			switch(str) {
			case "push" :
				st.push(sc.nextInt());
				break;
			case "pop" :
				st.pop();
				break;
			case "size" :
				st.size();
				break;
			case "empty" :
				st.empty();
				break;
			case "top":
				st.top();
				break;
			}
		}
	}
}

class St {
	int[] arr;
	int count = -1;
	
	public St(int size) {
		arr = new int[size];
	}
	
	void push(int a) {
		count++;
		arr[count] = a;
	}
	void pop() {
		if(count < 0) {
			System.out.println(-1);
		}
		else {
			System.out.println(arr[count]);
			count--;	
		}
	}
	void size() {
		System.out.println(count + 1);
	}
	void empty() {
		if (count < 0) {
			System.out.println(1);
		}
		else {
			System.out.println(0);
		}
	}
	void top() {
		if(count < 0) {
			System.out.println(-1);
		}
		else {
			System.out.println(arr[count]);
		}
	}
}

회고

기본 생성자를 추가하지 않아 배열에서 런타임에러가 발생

profile
백엔드 호소인

0개의 댓글