题目:用两个栈实现一个队列。实现它的两个函数appendTail和deleteHead,分别完成队列尾部插入节点和在队列头部删除节点的功能。
下面是java代码:
package Stackqueue;
import java.util.Stack;
public class QueueWithTwoStacks {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public QueueWithTwoStacks() {
this.stack1 = new Stack<Integer>();
this.stack2 = new Stack<Integer>();
}
public void appendTail(int[] a) {
for (int i = 0; i < a.length; i++) {
stack1.push(a[i]);
}
}
public int deleteHead() {
while (!stack1.isEmpty()) {
int data = stack1.pop();
stack2.push(data);
}
int number = stack2.pop();
return number;
}
public static void main(String[] args) {
int a[] = { 1, 2, 3, 4, 5, 6 };
QueueWithTwoStacks queueWithTwoStacks = new QueueWithTwoStacks();
queueWithTwoStacks.appendTail(a);
System.out.println(queueWithTwoStacks.deleteHead());
}
}
题目:用两个队列实现栈的功能,即pop函数和push函数
java代码:
package Stackqueue;
import java.util.LinkedList;
import java.util.Queue;
public class StackWithTowQueue {
private Queue<Integer> queue1;
private Queue<Integer> queue2;
public StackWithTowQueue() {
this.queue1 = new LinkedList<Integer>();
this.queue2 = new LinkedList<Integer>();
}
public void push(int vaule) {//
if (queue1.size() == 0 && queue2.size() == 0)
queue1.add(vaule);
if (queue1.size() != 0) {
queue1.add(vaule);
} else if (queue2.size() != 0) {
queue2.add(vaule);
}
}
public int pop() {
if (queue1.size() == 0 && queue2.size() == 0)
return 0;
int re = 0;
if (queue1.size() != 0 && queue2.size() == 0) {
while (queue1.size() > 1) {
re = queue1.remove();
queue2.add(re);
}
re = queue1.remove();
} else if (queue2.size() != 0 && queue1.size() == 0) {
while (queue2.size() > 1) {
re = queue2.remove();
queue1.add(re);
}
re = queue2.remove();
}
return re;
}
public static void main(String[] args) {
int a[] = { 1, 2, 3 };
StackWithTowQueue stackWithTowQueue = new StackWithTowQueue();
for (int i = 0; i < a.length; i++) {
stackWithTowQueue.push(a[i]);
}
for (int i = 0; i < a.length; i++) {
System.out.println(stackWithTowQueue.pop());
}
}
}