Stack to Queue, Queue to Stack

타마타마·2022년 9월 23일
0

Stack to Queue

스택을 뒤집으면 queue가 됨. >> stack 2개를 사용하여 만들기

class makeQueue{
	Stack<Integer> oldStack;
    Stack<Integer> newStack;
    
    public makeQueue(){
    	oldStack = new Stack<>();
        newStack = new Stack<>();
    }
    
    public offerQ(int a){
    	oldStack.push(a);
    }
    
    public pollQ(){
    	int result = -1;
        
        if(newStack.isEmpty()){
        	while(!oldStack.isEmpty()){
            	newStack.push(oldStack.pop());
            }
        }
        
        result = newStack.pop();
     
     	if(!newStack.isEmpty()){
        	while(!newStack.isEmpty()){
            	oldStack.push(newStack.pop());
            }
        }
     
    }
	return result;
}

Queue to Stack

class makeStack{
	Queue<Integer> mainQ;
    Queue<Integer> tempQ;
    
    public makeStack(){
    	mainQ = new LinkedList<>();
        tempQ = new LinkedList<>();
    }
    
    public void pushS(int a){
   		mainQ.offer(a);
    }
    
    public void popS(){
    	int result = -1;
        
        if(mainQueue.isEmpty()) {
			return -1;
		}
        
        while(mainQ.size!=1){
            tempQ.offer(mainQ.poll());
        }
        result = mainQ.poll();
        
        
        if(!tempQ.isEmpty()){
        	while(!tempQ.isEmpty()){
            	mainQ.offer(tempQ.poll());
            }
        }
       return result;
    }
}

0개의 댓글