您的位置:首页 > Web前端

剑指Offer-7-用两个栈实现队列/用两个队列实现栈

2015-09-26 19:04 399 查看

1.两个栈实现队列

import java.util.Stack;

public class CQueue<T> {
private Stack<T> s1 = new Stack<>(), s2 = new Stack<>();

public void EnQueue(T value) {
s1.push(value);
}

public T DeQueue() throws Exception {
while (!s1.isEmpty()) {
T value = s1.pop();
s2.push(value);
}
if (!s2.isEmpty()) {
return s2.pop();
} else {
throw new Exception("queue is empty");
}
}

public static void main(String[] args) throws Exception {
CQueue<Integer> q = new CQueue<>();
q.EnQueue(1);
q.EnQueue(2);
q.EnQueue(3);
System.out.println(q.DeQueue());
System.out.println(q.DeQueue());
System.out.println(q.DeQueue());
}
}


2.两个队列实现栈

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

public class CStack<T> {
private Queue<T> q1 = new LinkedList<>(), q2 = new LinkedList<>();

public void push(T value) {
if (!q2.isEmpty()) {
q2.add(value);
} else {
q1.add(value);
}
}

public T pop() throws Exception {
if (q1.isEmpty() && q2.isEmpty()) {
throw new Exception("stack is empty.");
}
T head = null;
if (q1.isEmpty()) {
while (q2.size() > 1) {
T v = q2.poll();
q1.add(v);
}
head = q2.poll();
} else {
while (q1.size() > 1) {
T v = q1.poll();
q2.add(v);
}
head = q1.poll();
}
return head;
}

public static void main(String[] args) throws Exception {
CStack<Integer> s = new CStack<>();
s.push(1);
s.push(2);
s.push(3);
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 剑指Offer