数据结构----Java中栈与队列相互实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013132035/article/details/82663927

栈:先进后出;队列:先进先出,FIFO

利用两个队列实现栈的功能

//利用两个队列实现栈
import java.util.Queue;
import java.util.LinkedList;

public class QueueToStack{
    Queue<Integer> queue1 = new LinkedList<Integer>();
    Queue<Integer> queue2 = new LinkedList<Integer>();
    
    //队列模拟进栈
    public static void push(int item){
        if(queue1.isEmpty() && queue2.isEmpty()){
            queue1.add(item);
            return;
        }
        if(queue1.isEmpty()){
            queue2.add(item);
            return;
        }
        if(queue2.isEmpty()){
            queue1.add(item);
            return;
        }    
    }
    
    //队列模拟出栈
    public static int pop(){
        if(queue1.isEmpty() && queue2.isEmpty()){
            try{
                throw new Exception("栈为空");
            }catch(Exception e){
                e.printStackTrace();
            }
        }    
        if(queue1.isEmpty()){
            while(queue2.size() > 1){
                queue1.add(queue2.poll());
            }
            return queue2.poll();
        }
        if(queue2.isEmpty()){
            while(queue1.size() > 1){
                queue2.add(queue1.poll());
            }
            return queue1.poll();
        }
        return 0;
    }
}

利用两个栈实现队列的功能

//利用两个栈实现队列的功能
import java.util.Stack;
public class StackToQueue{
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    //栈实现元素进队列
    public static void add(int item){
        if(stack1.isEmpty() && stack2.isEmpty()){
            stack1.push(item);
            return;
        }
        if(stack1.isEmpty()){
            stack2.push(item);
            return;
        }
        if(stack2.isEmpty()){
            stack1.push(item);
            return;
        }
    }

    //栈实现元素出队列
    public static void poll(){
        if(stack1.isEmpty() && stack2.isEmpty()){
            try{
                throw new Exception("队列为空");
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        if(stack1.isEmpty()){
            while(stack2.size() > 1){
                stack1.push(stack2.pop());
            }
            return stack2.pop();
        }
        if(stack2.isEmpty()){
            while(stack1.size() > 1){
                stack2.push(stack1.pop());
            }
            return stack1.pop();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/u013132035/article/details/82663927