Developer MJ

[Java] Stack 본문

Programming/Code

[Java] Stack

MIN JOON 2019. 2. 13. 10:11

한 쪽 끝에서만 자료를 넣거나 뺄 수 있는 선형 구조(LIFO - Last In First Out)

 

N(2<= N <=100)개의 수를 Stack에 넣은 후 하나씩 꺼내 화면에 출력

 

 

 
import java.util.Scanner;
 
class Solution {
 
    static final int MAX_N = 100;
 
    static int top;
    static int stack[] = new int[MAX_N];
 
    static void stackInit()
    {
        top = 0;
    }
 
    static boolean stackIsEmpty()
    {
        return (top == 0);
    }
 
    static boolean stackIsFull()
    {
        return (top == MAX_N);
    }
 
    static boolean stackPush(int value)
    {
        if (stackIsFull())
        {
            System.out.println("stack overflow!");
            return false;
        }
        stack[top] = value;
        top++;
 
        return true;
    }
 
    static Integer stackPop()
    {
        if (top == 0)
        {
            System.out.println("stack is empty!");
            return null;
        }
 
        top--;     
        Integer value = new Integer(stack[top]);
 
        return value;
    }
 
    public static void main(String arg[]) throws Exception {
        Scanner sc = new Scanner(System.in);
         
        int T = sc.nextInt();
 
        for (int test_case = 1; test_case <= T; test_case++)
        {
            int N = sc.nextInt();
 
            stackInit();
            for (int i = 0; i < N; i++)
            {
                int value = sc.nextInt();
                stackPush(value);
            }
 
            System.out.print("#" + test_case + " ");
 
            while (!stackIsEmpty())
            {
                Integer value = stackPop();
                if (value != null)
                {
                    System.out.print(value.intValue() + " ");
                }
            }
            System.out.println();
        }
        sc.close();
    }
}


 

'Programming > Code' 카테고리의 다른 글

[Java] 삽입 정렬 (Insertion Sort)  (0) 2019.04.15
[Java] Queue  (0) 2019.02.13
[Java] BlobSize Algorithm 문제  (0) 2017.10.12
[Java] N_Queens Algorithm 문제  (0) 2017.10.12
[Java] Maze 미로찾기 Algorithm 문제  (0) 2017.10.12