首页 > 其他 > 详细

225. Implement Stack using Queues

时间:2016-07-12 23:19:46      阅读:280      评论:0      收藏:0      [点我收藏+]
import java.util.LinkedList;
import java.util.Queue;

class MyStack {
    
    Queue<Integer> q1=new LinkedList<Integer>();
    Queue<Integer> q2=new LinkedList<Integer>();
    
    // Push element x onto stack.
    public void push(int x) {
        if(q1.isEmpty()&&q2.isEmpty())
        {
            q1.add(x);
        }
        else
        {
            if(!q1.isEmpty())
                q1.add(x);
            else
                q2.add(x);
        }
        
    }

    // Removes the element on top of the stack.
    public void pop() {
        
        if(!q1.isEmpty())
        {
            while(q1.size()!=1)
            {
                q2.add(q1.poll());
            }
            q1.poll();
        }
        else
        {
            while(q2.size()!=1)
            {
                q1.add(q2.poll());
            }
            q2.poll();
        }
        
    }

    // Get the top element.
    public int top() {
        int res=0;
        if(!q1.isEmpty())
        {
            while(!q1.isEmpty())
            {
                res=q1.poll();
                q2.add(res);
            }
        }
        else
        {
            while(!q2.isEmpty())
            {
                res=q2.poll();
                q1.add(res);
            }
        }
        return res;
        
    }

    // Return whether the stack is empty.
    public boolean empty() {
        if(q1.isEmpty()&&q2.isEmpty())
            return true;
        else
            return false;
    }
}

 

225. Implement Stack using Queues

原文:http://www.cnblogs.com/aguai1992/p/5664966.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!