/ JAVAJUNGSUK

Ch11-19~21. Stack, Queue

자바의 정석 기초편

0. 목차



Chapter11. 컬렉션 프레임웍

Ch11 - 19. Stack과 Queue의 활용

Ch11 - 20. Stack과 Queue의 활용 예제1

Ch11 - 21. Stack과 Queue의 활용 예제2



Ch11 - 19. Stack과 Queue의 활용


▶ Stack 활용 예

▷ 수식 계산
▷ 수식 괄호 검사
▷ 워드르로세서의 undo/redo(작업 취소/되돌리기)
▷ 웹브라우저의 ←/→ 버튼


▶ Queue 활용 예

▷ 최근 사용 문서
▷ 인쇄 작업 대기 목록
▷ 버퍼(buffer)



Ch11 - 20. Stack과 Queue의 활용 예제1


▶ 수식 괄호 검사 : Stack 활용

777*6 + ((99*2) + (222*2))"777*6 + ((99*2) + (222*2))"
Stack st = new Stack();

String gualhoGumsa = "777*6 + ((99*2) + (222*2))";
gualhoGumsa.length()만큼 돌면서 괄호 하나 하나 검사
( : 여는 괄호는 Stack에 넣음
) : 닫는 괄호는 Stack에서 뺌
for (int i = 0; i < gualhoGumsa.length(); i++) {
    char ch = gualhoGumsa.charAt(i);
    
    if (ch == '(') {
        st.push(ch + "");
    } else if (ch == ')') {
        st.pop();
    }
}
System.out.println(gualhoGumsa.length());

// console
26

[7][7][7][*][6][ ][+][ ][(][(][9][9][*][2][ ][+][ ]...
[] 하나 하나 검사
[(] : st.push()
[)] : st.pop()


▷ () 정상 : ok, () 비정상 : error
if (st.isEmpty()) {
    System.out.println("ok");
} else {
    System.out.println("error");
}
▷ 전체
public static void main(String[] args) {
    Stack st = new Stack();
    
    String gualhoGumsa = "777*6 + ((99*2) + (222*2))";
    
    for (int i = 0; i < gualhoGumsa.length(); i++) {
        char ch = gualhoGumsa.charAt(i);
        
        if (ch == '(') {
            st.push(ch + "");
        } else if (ch == ')') {
            st.pop();
        }
        }
        
        if (st.isEmpty()) {
            System.out.println("ok");
        } else {
            System.out.println("error");
        }
    }
}

// console
ok



Ch11 - 21. Stack과 Queue의 활용 예제2


▶ 최근 5개의 기록 불러오기 : Queue 활용

▷ 최대 5개 지정
static Queue q = new LinkedList();

static final int MAX_SIZE = 5;
▷ 화면에서 입력받기
while (true) {
    System.out.println("INPUT> ");
    
    Scanner scanner = new Scanner(System.in);
    String input = scanner.nextLine().trim();
}
▷ 화면에서 아무것도 입력하지 않고 엔터 쳤을 때, 계속
if ("".equals(input)) continue;
▷ q/Q = 종료
if ("q".equalsIgnoreCase(input)) System.exit(0);
▷ h/H = 도움말
else if (input.equalsIgnoreCase("h")) {
    System.out.println("s : 최근 기록 " + MAX_SIZE + "개");
    System.out.println("q : 종료");
}
▷ input 저장
public static void save(String input) {

    if (!"".equals(input)) q.offer(input); // 아무것도 안 적은 것만 아니면 화면에서 입력한 거 다 Queue로 저장
    
    if (q.size() > MAX_SIZE) q.remove(); // input이 6개 넘어가면 저장X 삭제
}
▷ input 저장한거 보여주기
LinkedList list = (LinkedList)q; // input을 Queue로 offer → LinkedList list에 담음

final int SIZE = list.size(); // input 저장한 개수

for (int i = 0; i < SIZE; i++) {
    System.out.println((i+1) + "." + list.get(i)); // 순서대로 input 뽑아서 보여 줌
}
▷ s/S = 최근 기록 MAX_SIZE개
else if (input.equalsIgnoreCase("s")) {
    save(input);
    
    LinkedList list = (LinkedList)q;
    
    final int SIZE = list.size();
    for (int i = 0; i < SIZE; i++) {
        System.out.println((i+1) + "." + list.get(i));
    }
}
▷ 전체
package baek;

import java.util.*;

public class PlayQueue {
	
	static Queue q = new LinkedList();
	
	static final int MAX_SIZE = 5;
	
	public static void main(String[] args) {
		System.out.println("h, s, q");
		
		while (true) {
			System.out.printf("\nINPUT> ");
			
			Scanner scanner = new Scanner(System.in);
			String input = scanner.nextLine().trim();

			if ("".equals(input)) continue;
			
			if (input.equalsIgnoreCase("q")) {
				System.exit(0);
			} else if (input.equalsIgnoreCase("h")) {
				System.out.println("s : 최근 기록 " + MAX_SIZE + "개");
				System.out.println("q : 종료");
			} else if (input.equalsIgnoreCase("s")) {
				save(input);
				
				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);
			}
		}
	}

	public static void save(String input) {
		
		if (!"".equals(input)) q.offer(input);
		
		if (q.size() > MAX_SIZE) q.remove();
	}
}
// console

h, s, q

INPUT> aaa
aaa

INPUT> bbb
bbb

INPUT> ccc
ccc

INPUT> ddd
ddd

INPUT> eee
eee

INPUT> s
1.bbb
2.ccc
3.ddd
4.eee
5.s

INPUT> fff
fff

INPUT> ggg
ggg

INPUT> hhh
hhh

INPUT> iii
iii

INPUT> lll
lll

INPUT> kkk
kkk

INPUT> s
1.hhh
2.iii
3.lll
4.kkk
5.s

INPUT> h
s : 최근 기록 5
q : 종료

INPUT> q