Stack

KH·2023년 5월 24일
0
post-thumbnail

source: https://www.acmicpc.net/problem/10828
ref: Googling based on chatGPT's response (There could be some errors)

정수를 저장하는 스택을 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.

sol1) Stack 클래스 import

class vs interface
In general, you would use a class when you want to define a concrete object with specific attributes and behaviors, while an interface is used to define a contract that classes can implement to provide certain functionality.
Interfaces are often used to achieve abstraction, decoupling implementation details from the client code.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

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());
        Stack<Integer> stack = new Stack<>();

        for(int i = 0; i<N;i++) { 
            String input = br.readLine();
            String[] result = input.split(" ");

            if (result[0].equals("push")) {
                int pushNum = Integer.parseInt(result[1]);
                stack.push(pushNum);
            } else if (result[0].equals("pop")) {
                if (stack.empty())
                    System.out.println(-1);
                else {
                    System.out.println(stack.pop());
                }
            } else if (result[0].equals("size")) {
                System.out.println(stack.size());
            } else if (result[0].equals("empty")) {
                System.out.println(stack.empty() ? 1 : 0);
            } else if (result[0].equals("top")) {
                if (stack.empty())
                    System.out.println(-1);
                else
                    System.out.println(stack.peek());
            }
        }
    }
}

sol2) Stack 클래스 구현

topIndex가 가리키는 위치 기준으로 메서드 구현
단, stackArray의 값들은 자료구조로서의 Stack을 나타내지 않음.
예컨대 아래에서 value_1을 pull한 경우 topIndex는 value_0을 가리키지만
value_1을 삭제하지는 않는다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class StackArray<T> {
    private int maxSize;
    private int topIndex;
    private T[] stackArray;

    public StackArray(int size) {
        maxSize = size;
        topIndex = -1;
        stackArray = (T[]) new Object[maxSize];
    }

    public void push(T value) {
        if (topIndex == maxSize - 1) {
            throw new IllegalStateException("Stack overflow");
        }
        stackArray[++topIndex] = value;
    }

    public T pop() {
        if (topIndex == -1) {
            throw new IllegalStateException("Stack underflow");
        }
        return stackArray[topIndex--];
    }

    public int size() {
        return topIndex + 1;
    }

    public boolean isEmpty() {
        return topIndex == -1;
    }

    public T top() {
        if (topIndex == -1) {
            throw new IllegalStateException("Stack is empty");
        }
        return stackArray[topIndex];
    }
}

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());

        StackArray<Integer> stackArray = new StackArray<>(N);

        for (int i = 0; i < N; i++) {
            String input = br.readLine();
            String[] result = input.split(" ");

            if (result[0].equals("push")) {
                int pushNum = Integer.parseInt(result[1]);
                stackArray.push(pushNum);
            } else if (result[0].equals("pop")) {
                if (stackArray.isEmpty())
                    System.out.println(-1);
                else
                    System.out.println(stackArray.pop());
            } else if (result[0].equals("size")) {
                System.out.println(stackArray.size());
            } else if (result[0].equals("empty")) {
                System.out.println(stackArray.isEmpty() ? 1 : 0);
            } else if (result[0].equals("top")) {
                if (stackArray.isEmpty())
                    System.out.println(-1);
                else
                    System.out.println(stackArray.top());
            }
        }
    }
}

StackArray<T>는 generic class임을 나타낸다.

A generic class in Java is a class that is parameterized with one or more type parameters. It allows you to create a class that can work with different types without sacrificing type safety. The type parameter(s) are specified in angle brackets (<>) when declaring the class.

profile
What, How, Why

0개의 댓글

관련 채용 정보