[Java] ArrayList로 구현한 Memory구조(Stack,Pop)

ArrayList를 처음 배울때 만들어봤었던 콘솔 Stack , Pop입니다. ArrayList의 add메서드와 remove메서드를 활용하면 쉽게 구현이 가능합니다.


Main.java

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
		
    Queue qu = new Queue();
    Stack st = new Stack();
		
    while(true){	
        System.out.println("1.스택 2.큐");
	Scanner sc = new Scanner(System.in);
	int select = sc.nextInt();
		
        switch (select) {
            case 1:
		System.out.println("1.푸쉬 2.팝");
		select=sc.nextInt();
		if(select==1){
			System.out.println("숫자를 입력해주세요");
			select = sc.nextInt();
			st.Input(select);
			st.Output();
		}else if(select==2){
			System.out.println("팝되었습니다.");
			st.Pop();
			st.Output();
		}
		break;
	    case 2:
		System.out.println("1.푸쉬 2.팝");
		select=sc.nextInt();
		if(select==1){
			System.out.println("숫자를 입력해주세요");
			select = sc.nextInt();
			qu.Input(select);
			qu.Output();
		}else if(select==2){
			System.out.println("팝되었습니다.");
			qu.Pop();
			qu.Output();
		}
		break;

	    default:
		break;
	   }
	}
   }
}


Memory.java

import java.util.ArrayList;

public class Memory {
    ArrayList<Integer>list = new ArrayList<>();
	
    public void Input(int a){
	list.add(a);
    }
	
    public void Output(){
	System.out.println(list);
    }
}


Queue.java

public class Queue extends Memory{

    public void Pop(){
	list.remove(0);
    }
}



Stack.java

public class Stack extends Memory{

    public void Pop(){
	list.remove(list.size()-1);
    }
}


댓글

Designed by JB FACTORY