11-19~21 Stack & Queue 활용

oyeon·2020년 12월 24일
0

Java 개념

목록 보기
28/70

스택의 활용 예 - 수식계산, 수식괄호검사, 워드프로세서의 undo/redo, 웹브라우저의 뒤로/앞으로

큐의 활용 예 - 최근사용문서, 인쇄작업 대기목록, 버퍼(buffer)

스택을 활용한 수식괄호검사 예제

public static void main(String[] args){
    Stack st = new Stack();
    String expression = "((3+5)*8-2";
    
    try{
    	for(int i = 0; i < expression.length(); i++){
        	char ch = expression.charAt(i);
            
            if (ch == '(') {
            	st.push(ch);
            } else if (ch == ')'){
            	st.pop();
            }
        }
    	if(st.isEmpty()){
        	System.out.println("괄호가 일치합니다.");
        } else{
        	System.out.println("괄호가 일치하지 않습니다.");
        }
    } catch(EmptyStackException e){
    	System.out.println("괄호가 일치하지 않습니다.");
    }
}

큐를 활용한 최근사용단어 예제

static Queue q = new LinkedList();
static final int MAX_SIZE = 5;

public static void main(String[] args){
	System.out.println("help를 입력하면 도움말을 볼 수 있습니다.");
	
	while(true) {
		System.out.println(">>");
		try {
			Scanner s = new Scanner(System.in);
			String input = s.nextLine().trim(); // trim()-앞뒤 공백 삭제
			
			if("".equals(input)) continue;
			
			if(input.equalsIgnoreCase("q")){
				System.exit(0);					
			}else if(input.equalsIgnoreCase("help")) {
				System.out.println("help - 도움말을 보여줍니다.");
				System.out.println("q 또는 Q - 프로그램을 종료합니다.");
				System.out.println("history - 최근에 입력한 명령어를 "
						+ MAX_SIZE + "개 보여줍니다.");					
			}else if(input.equalsIgnoreCase("history")) {
				save(input);	// 입력받은 명령어를 저장하고,
				// LinkedList의 내용을 보여준다.
				LinkedList list = (LinkedList)q;
				
				final int SIZE = list.size();
				for(int i = 0; i < SIZE; i++) 
					System.out.println((i+1)+"."+list.get(i));
			} else {
				save(input);
				System.out.println(input);
			}
		} catch(Exception e) {
			System.out.println("입력오류입니다.");				
		}
	}	// while(true)
}	// main()
public static void save(String input) {
	// queue에 저장한다.
	if(!"".equals(input))
		q.offer(input);
	
	// queue의 최대 크기를 넘으면 제일 처음 입력된 것을 삭제한다.
	if(q.size() > MAX_SIZE)	// size()는 Collection 인터페이스에 정의
		q.remove(); // q.poll() 사용가능
}
profile
Enjoy to study

0개의 댓글