JAVA

[Java] Collections Framework - Stack & Queue

SangRok Jung 2022. 7. 21. 21:47
반응형

 

 

 

 

Stack Class,
Queue<E> Interface


Stack & Queue

 

 

Stack LIFO 구조 ArrayList로 만드는데 적합
Queue FIFO 구조 LinkedList로 만드는데 적합

 

 

스택 활용의 예

  • 수식계산, 수식괄호검사, 워드프로세서의 undo/redo, 웹브라우저의 뒤로/앞으로

 

큐의 활용 예

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

 

 

 

 

 

 

 

 

 

▶ Stack 메서드

메서드 설명
boolean empty() Stack이 비어있는지 알려준다.
Object peek() Stack의 맨 위에 저장된 객체를 반환. pop()과 달리 Stack에서 객체를 꺼내지는 않음(비었을 때 EmptyStackException 발생)
Object pop() Stack의 맨 위의 저장된 객체를 꺼낸다. (비었을 때는 EmptyStackException 발생)
Object push(Object item) Stack에 객체(item)을 저장한다.
int search(Object o) Stack에 주어진 객체(o)를 찾아서 그 위치를 반환. 못 찾으면 -1을 반환. (배열과 달리 위치는 0이 아닌 1부터 시작. 맨위의 요소가 1)

 

 

 

 

▶ Queue 메서드

메서드 설명
boolean add(Object o) 지정된 객체를 Queue에 추가한다. 성공하면 true를 반환. 저장공간이 부족하면 IllergalStateException 발생
Object remove() Queue에서 객체를 꺼내 반환. 비어있으면 NoSuchElementException 발생
Object element() 삭젱벗이 요소를 읽어온다. peek와 달리 Queue가 비었을 때 NoSuchElementException발생
boolean offer(Object o) Queue에 객체를 저장. 성공하면 true. 실패하면 false를 반환
Object poll() Queue에서 객체를 꺼내서 반환, 비어 있으면 null을 반환
Object peek() 삭제없이 요소를 읽어 온다. Queue가 비어 있으면 null을 반환.

 

 

 

* Queue는 메모리가 부족하면 예외를 발생시킨다.

 

 

Queue Method

  • 예외 발생
    • add()
    • remove()
    • element()

 

  • 예외 미발생
    • offer()
    • poll()
    • peek()

 

 

 

▶ 간단한 Stack & Queue 구현

    public static void main(String[] args) {
        Queue q = new LinkedList(); //Q인터페이스의 구현
        Stack st = new Stack();

        st.push("0");
        st.push("1");
        st.push("2");

        q.offer("0");
        q.offer("1");
        q.offer("2");

        System.out.println("=Stack=");
        while(!st.isEmpty()){
            System.out.println(st.pop()); // Stack에서 요소 하나를 꺼내
        }

        System.out.println("=Queue");
        while(!q.isEmpty()){
            System.out.println(q.poll()); // Queue에서 요소 하나를 꺼내
        }
    }

 

 

 

 

 

▶ Stack의 활용 예제

public class sample {
    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); // i인덱스의 문자 추출
                if (ch == '('){
                    st.push(ch + "");
                }
                else if (ch == ')'){
                    st.pop();
                }
            }

            if (st.isEmpty()) {
                System.out.println("괄호가 일치합니다.");
            }
            else{
                System.out.println("괄호가 일치하지 않습니다.");
            }
        }
        catch (Exception e) {
            System.out.println("Error 괄호가 일치하지 않습니다.");
        }
    }
}

 

 

 

 

 

 

▶ Queue의 활용 예제1

    public static void main(String[] args) {
        // queue는 interface, 기능 집합이다.
        // queue를 가지고 linkedList를 구현하겠다.
        // queue를 가지고 ArrayList는 구현 되지 않는다.
        Queue<String> q = new LinkedList<String>();
        String temp;

        // offer와 add는 같다.
        q.offer("data1");
        q.offer("data2");
        q.offer("data3");

        temp = q.peek();
        System.out.println("peek() : " + temp);

        temp = q.poll();
        System.out.println("poll() : " + temp);

        temp = q.poll();
        System.out.println("poll() : " + temp);

        temp = q.poll();
        System.out.println("poll() : " + temp);

        temp = q.poll();
        System.out.println("poll() : " + temp); //null


        // Exception Code
        // remove
        try{
            temp = q.remove();
        }
        catch (Exception e){
             System.out.println("remove() : " + temp);
        }
        // element
        try{
            temp = q.element();
        }
        catch (Exception e){
            System.out.println("element() : " + temp);
        }
    }

 

 

 

▶ Queue의 활용 예제2

public class sample {
    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.print(">>");
            try{
                // 화면으로부터 라인단위로 입력받는다.
                Scanner s = new Scanner(System.in);
                String input = s.nextLine().trim(); //trim() : 양쪽 끝의 공백 제거

                if("".equals(input))
                    continue;

                if(input.equalsIgnoreCase("q")) // equalsIgnoreCase() : 문자열을 대소문자 상관없이 비교 
                    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("입력오류입니다.");
            }
        }
    }

    public static void save(String input){
        // queue에 저장한다.
        if(!"".equals(input)){
            q.offer(input);     // Queue에 객체를 저장
        }
        if(q.size() > MAX_SIZE){
            q.remove();         // Queue에 객체를 꺼내 반환.
        }
    }
}

 

 

 

반응형

'JAVA' 카테고리의 다른 글

[Java] Collections Framework - Set  (0) 2022.07.26
[Java] Collections Framework - Arrays  (0) 2022.07.24
[Java] Collections Framework - List Interface  (0) 2022.07.21
[Java] Collections Framework  (0) 2022.07.21
[Java] Calendar Exercise (예제)  (0) 2022.07.19