신규 블로그를 만들었습니다!

2020년 이후부터는 아래 블로그에서 활동합니다.

댓글로 질문 주셔도 확인하기 어려울 수 있습니다.

>> https://bluemiv.tistory.com/
package stack;

import java.util.LinkedList;
import java.util.Queue;

public class StackUsingQueue {

    private Queue main_queue;
    private Queue temp_queue;

    StackUsingQueue() {
        main_queue = new LinkedList();
        temp_queue = new LinkedList();
    }

    // 1 2 3 4
    // 4
    // 1 2 3
    void push(Object item) {
        main_queue.add(item);
    }

    Object pop() {
        if (!main_queue.isEmpty()) {
            Object result = null;
            while(true) {
                result = main_queue.poll();
                if(main_queue.isEmpty()) {
                    // 마지막 값을 반환
                    break;
                }else {
                    temp_queue.add(result);    
                }
            }// end while
            
            // 다시 메인 큐에 넣어 줌
            while(!temp_queue.isEmpty()) {
                main_queue.add(temp_queue.poll());
            }
            
            return result;
            
        }else {
            return null;
        }
    }
    
    public static void main(String[] args) {
        StackUsingQueue stack = new StackUsingQueue();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        System.out.println(stack.pop());
        System.out.println(stack.pop());

        stack.push(4);
        stack.push(5);
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
    }
}​

 

  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기