您的位置:首页 > 产品设计 > UI/UE

LeetCode---Implement Queue Using Stacks、Implement Stack Using Queues解题分析

2016-05-13 11:49 423 查看
题意描述:用两个栈来实现一个队列的操作,用两个队列来实现一个栈的操作

解题思路

用栈实现队列的操作:栈S1、S2分别用于入队、出队

(1)入队:若S1不满直接将新元素放入S1,若S1满则将S1中元素转入S2,然后再将新元素放入S1;

(2)出队:若S2不空则直接从S2弹出栈顶元素,若S2空则先将S1元素转到S2再弹出S2栈顶元素;

public class ImplementQueueUsingStacks {

Stack<Integer> s1 = new Stack<>();
Stack<Integer> s2 = new Stack<>();

// Push element x to the back of queue.
public void push(int x) {
s1.push(x);
}

// Removes the element from in front of queue.
public void pop() {
if(!s2.isEmpty())
s2.pop();
else{
while(!s1.isEmpty()) s2.push(s1.pop());
s2.pop();
}
}

// Get the front element.
public int peek() {
if(!s2.isEmpty())
return s2.peek();
else{
while(!s1.isEmpty())
s2.push(s1.pop());
return s2.peek();
}
}

// Return whether the queue is empty.
public boolean empty() {
return s1.empty() && s2.empty();
}

public static void main(String[] args) {
ImplementQueueUsingStacks s = new ImplementQueueUsingStacks();
s.push(1);
s.push(2);
s.push(3);
while(!s.empty()){
System.out.println(s.peek());
s.pop();
}
}

}


用队列实现栈的操作:声明队列Q1、Q2

(1)入栈:若Q1有元素、Q2为空,则将新元素加入Q2,然后将Q1元素转入Q2中(反过来也可以,只需要保证一个队列为空即可);

(2)出栈:将有元素的队列输出即可;

public class ImplementStackUsingQueues {
// Push element x onto stack.
Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();

public void push(int x) {
q1.offer(x);
}

// Removes the element on top of the stack.
public void pop() {
while(q1.size()>1) q2.offer(q1.poll());
q1.poll();
Queue<Integer> q = q1;
q1 = q2;
q2 = q;
}

// Get the top element.
public int top() {
while(q1.size()>1) q2.offer(q1.poll());
int x = q1.poll();
q2.offer(x);
Queue<Integer> q = q1;
q1 = q2;
q2 = q;
return x;
}

// Return whether the stack is empty.
public boolean empty() {
return q1.isEmpty();
}
public static void main(String[] args) {
// TODO Auto-generated method stub

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: