본문 바로가기
카테고리 없음

[JAVA] STACK / QUEUE

STACK / QUEUE






package Test3;
 
import java.util.Scanner;
 
abstract class Memory{
    int i;
    int []arr;
 
    Memory(){
        arr = new int[20];
        i=0;
    }
    void push() {
        if(i>19) {
            System.out.println("더 이상 입력 할 수 없습니다.");
        }else if(i<19) {
            System.out.println("입력 하세요.");
            arr[i] = new Scanner(System.in).nextInt();
            i++;
        }
    }
    abstract void pop();
}
 
class Stack extends Memory{
    @Override
    void pop() {
        if(i==0) {
            System.out.println("더 이상 값이 없습니다.");
        }else {
            System.out.println(arr[--i]);
        }
    }
}
class Queue extends Memory{
    @Override
    void pop() {
        if(i==0) {
            System.out.println("더 이상 값이 없습니다.");
        }else {
            System.out.println(arr[0]);
            for (int j = 0; j < i-1; j++) {
                arr[j] = arr[j+1];
            }i--;
        }
    }
}
 
 
 
public class StackQueue {
    public static void main(String[] args) {
 
        Memory memory;
        Stack stack = new Stack();
        Queue queue = new Queue();
 
        while(true) {
            System.out.println("1.Stack 2.Queue 3.End");
            int num = new Scanner(System.in).nextInt();
            switch(num) {
            case 1 :
                memory = stack;
                System.out.println("생성할 메모리 : ");
                int n1 = new Scanner(System.in).nextInt();
                for (int i = 0; i < n1; i++) {
                    memory.push();
                }
                for (int i = 0; i < n1; i++) {
                    memory.pop();
                }
                break;
            case 2 :
                memory = queue;
                System.out.println("생성할 메모리 : ");
                int n2 = new Scanner(System.in).nextInt();
                for (int i = 0; i < n2; i++) {
                    memory.push();
                }
                for (int i = 0; i < n2; i++) {
                    memory.pop();
                }
                break;
            case 3:
                System.out.println("종료");
                return;
            }
        }
    }  
}