Dev.baelanche

[백준 10828] 스택 본문

Data Structure & Algorithm/PS - JAVA

[백준 10828] 스택

baelanche 2019. 4. 3. 20:12
반응형

 

스택으로 입출력하면 되는 간단한 문제이다.

 

본 문제에서는 직접 구현한 스택으로 풀었다.

 

 

import java.util.Scanner;

public class Main {

    Node head;
    int size = 0;

    class Node {
        Node prev;
        Object value;

        Node(Object value) {
            this.value = value;
        }
    }

    public void push(Object value) {
        Node node = new Node(value);
        if(size >= 1)
            node.prev = head;
        head = node;
        size++;
    }

    public Object pop() {
        if(size == 0) {
            return -1;
        }

        Node temp = head;
        head = head.prev;
        size--;
        
        return temp.value;
    }

    public Object top() {
        if(size == 0) {
            return -1;
        }
        return head.value;
    }

    public int size() {
        return size;
    }
    
    public boolean isEmpty() {
        if(size == 0) return true;
        return false;
    }
    
    public String toString() {
        String str = "top [";
        Node temp = head;
        for(int i=0; i<size; i++) {
            str += temp.value;
            if(i != size-1) {
                temp = temp.prev;
                str += ", ";
            }
        }
        return str += "] bottom";
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int n = sc.nextInt();
        sc.nextLine();
        Main s = new Main();
        
        for(int i=0; i<n; i++) {
            String command = sc.nextLine();
            if(command.contains("push")) {
                int push = Integer.parseInt(command.split(" ")[1]);
                s.push(push);
            } else if(command.contains("pop")) {
                System.out.println(s.pop());
            } else if(command.contains("size")) {
                System.out.println(s.size());
            } else if(command.contains("empty")) {
                if(s.isEmpty()) System.out.println(1);
                else System.out.println(0);
            } else {
                System.out.println(s.top());
            }
        }
        sc.close();
    }
}

 

 

문제에서 요구하는대로 스택 클래스를 손보면서 진행했다.

반응형

'Data Structure & Algorithm > PS - JAVA' 카테고리의 다른 글

[백준 11052] 카드 구매하기  (0) 2019.04.03
[백준 9012] 괄호  (0) 2019.04.03
[백준 11727] 2xn 타일링 2  (0) 2019.04.02
[백준 11726] 2xn 타일링  (0) 2019.04.02
[백준 1904] 01타일  (0) 2019.04.02
Comments