用两个栈实现队列
1、栈的特点就是先进后出,而队列要做到先进先出,所以两个栈一个用来做入队操作(stack1)一个用来做出队操作(stack2)然后再把没有删完的元素再放到stack1中。具体代码实现过程如下:
private T[] stack;// 存储栈的元素的数组
// top表示栈顶的位置
private int top;
public SeqStack(){
this(10);
}
public SeqStack(int size){
this.stack = (T[])new Object[size];
this.top = 0;
}
public void push(T val){
if(full()){
// 栈如果满了,要进行内存2倍扩容
this.stack = Arrays.copyOf(this.stack,
this.stack.length*2);
}
this.stack[this.top] = val;
this.top++;
}
public void pop(T val){
if(empty())
return;
this.top–;
if(this.top < this.stack.length/2){
this.stack = Arrays.copyOf(this.stack, this.stack.length/2);
}
}
public T top(){
return this.stack[this.top - 1];
}
public boolean full(){
return this.top == this.stack.length;
}
public boolean empty(){
return this.top == 0;
-------------------------然后再实现两个栈实现一个队列-------------------------------
class Quene {
private SeqStack stack1;//入队操作
private SeqStack stack2;//出队操作
public void offer(E val){
stack1.push(val);
}
public E poll(E val){
E data=null;
while (!stack1.empty()){
data= stack1.pop();
stack2.push(data);
if(stack1.empty()){
break;
}
}
while (!stack2.empty()){
stack2.pop(val);
stack1.push(stack2.pop());
}
return data;
}
用两个队列实现栈
首先栈的特点是先进后出,队列的特点是先进先出,所以这里用两个队列,一个实现入栈操作,一个进行出栈操作。
public void offer(E val){
if(full()){
// 扩容
E[] newQue = Arrays.copyOf(this.que,
this.que.length*2);
int index = 0;
for(int i=this.front;
i != this.rear;
i=(i+1)%this.que.length){
newQue[index++] = this.que[i];
}
this.front = 0;
this.rear = index;
this.que = newQue;
}
this.que[this.rear] = val;
this.rear = (this.rear+1)%this.que.length;
}
/**
* 出队操作,并把出队的元素的值返回
*/
public E poll(){
if(empty()){
return null;
}
E front = this.que[this.front];
this.front = (this.front+1)%this.que.length;
return front;
}
/**
* 查看队头元素
* @return
*/
public E peek(){
if(empty()){
return null;
}
return this.que[this.front];
}
/**
* 判断队满
* @return
*/
public boolean full(){
return (this.rear+1)%this.que.length == this.front;
}
/**
* 判断队空
* @return
*/
public boolean empty(){
return this.rear == this.front;
}
}
----------------------------------两个队列实现一个栈 -----------------------------------
class SedStack <E> {
Queue<E> que1 = new Queue();
Queue<E> que2 = new Queue();
public void SedStack() {
this.que1 = que1;
this.que2 = que2;
}
public void push(E val) {
que1.offer(val);
}
public E pop() {
E data = null;
while (!que1.empty()) {
data = que1.poll();
que2.offer(data);
if (que1.empty()) {
break;
}
while (!que2.empty()) {
data = que2.poll();
que1.offer(data);
}
}
return data;
}
public E top() {
E data = null;
while (!que1.empty()) {
data = que1.poll();
que2.offer(data);
}
while (!que2.empty()) {
data = que2.poll();
que1.offer(data);
}
return data;
}
public boolean full(){
return que1.full();
}
public boolean empty(){
return que1.empty();
}
}