题目:用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deleteHead,分别完成在队列尾部插入结点和在队列头部删除结点的功能。
定义两个Stack分别stack1和stack2。添加一个元素:将这个元素压入stack1中;删除一个元素:当stack2中不为空时,在stack2中的栈顶元素是最先进入队列的元素,可以弹出。如果stack2为空时,把stack1中的元素逐个弹出并压入stack2。由于先进入队列的元素被压到stack1的底端,经过弹出和压入之后就处于stack2的顶端了,又可以直接弹出。
代码实现:
import java.util.Stack; class CQueue<T>{ private Stack<T> stack1; private Stack<T> stack2; private int size=0; public <T> CQueue(){ stack1=new Stack<>(); stack2=new Stack<>(); } public void appendTail(T node){ size++; stack1.push(node); } public T deleteHead() throws Exception{ if(stack2.empty()){ while(!stack1.empty()){ T node=stack1.pop(); stack2.push(node); } } if(stack2.empty()){ throw new Exception("queue is empty."); } T head=stack2.pop(); size--; return head; } public int size(){ return size; } } public class Solution{ public static void main(String[] args){ CQueue<Integer> q=new CQueue<Integer>(); q.appendTail(5); q.appendTail(6); q.appendTail(7); q.appendTail(8); while(q.size()>0){ try{ Integer i=q.deleteHead(); System.out.print(i+" "); }catch(Exception e){ e.printStackTrace(); } } try{ Integer i=q.deleteHead(); }catch(Exception e){ e.printStackTrace(); } } }
相关题目:
用两个队列实现一个栈。

代码实现:
import java.util.LinkedList; import java.util.Queue; class Stack<T>{ private Queue<T> queue1; private Queue<T> queue2; public <T> Stack(){ queue1=new LinkedList<>(); queue2=new LinkedList<>(); } //向非空的那个队列中压入数据 public void push(T data){ if(queue2.size()==0){ queue1.offer(data); }else{ queue2.offer(data); } } //非空的一个队列弹出数据至数据为空的队列里,直到最后一个元素。 //删除掉最后一个元素,栈为空时pop操作直接抛出异常。 public T pop() throws Exception{ T t=null; if(queue1.size()==0){ while(queue2.size()>1){ t=queue2.poll(); queue1.offer(t); } if(queue2.size()==1){ t=queue2.poll(); } }else{ while(queue1.size()>1){ t=queue1.poll(); queue2.offer(t); } if(queue1.size()==1){ t=queue1.poll(); } } if(t==null){ throw new Exception("Stack is empty"); } return t; } //判断栈是否为空 public boolean empty(){ boolean isEmpty=true; if(queue1.size()>0||queue2.size()>0){ isEmpty=false; } return isEmpty; } } public class Solution{ public static void main(String[] args){ Stack<Integer> stack=new Stack<>(); stack.push(1); stack.push(2); stack.push(3); stack.push(4); stack.push(5); stack.push(7); while(!stack.empty()){ try{ Integer i=stack.pop(); System.out.print(i+" "); }catch(Exception e){ e.printStackTrace(); } } try{ stack.pop(); }catch(Exception e){ e.printStackTrace(); } } }
posted on
浙公网安备 33010602011771号