数据结构-栈和队列
public class stackQueue { Stack<Integer> stack1=new Stack<>(); Stack<Integer> stack2=new Stack<>(); public void appendTail(int num){ if(stack2.empty()){ stack1.push(num); System.out.println(num+" push success!"); } else{ while(!stack2.empty()){ stack1.push(stack2.pop()); } stack1.push(num); System.out.println(num+" push success!"); } } public int deleteHead(){ int tmp = -1; if(stack2.size()==0){ while(!stack1.empty()){ tmp=stack1.pop(); stack2.push(tmp); } } else{ tmp=stack2.peek(); } if(tmp>0){ System.out.println(tmp+" pop success!"); } return stack2.pop(); } public void queueSize(){ System.out.println("queue total size: "+stack1.size()+stack2.size()); } public static void main(String[] args){ stackQueue sq = new stackQueue(); sq.appendTail(12); sq.appendTail(13); sq.appendTail(14); sq.deleteHead(); sq.deleteHead(); sq.appendTail(15); sq.deleteHead(); sq.queueSize(); } }
public class queueStack { private LinkedList<Integer> queue1=new LinkedList<>(); private LinkedList<Integer> queue2=new LinkedList<>(); public void push(int value) throws InterruptedException { if(queue2.isEmpty()){ queue1.addLast(value); } else{ while(!queue2.isEmpty()){ queue1.addLast(queue2.pollFirst()); } queue1.addLast(value); } System.out.println(value+" push success!"); } public void pop(){ int tmp=-1; if(!queue1.isEmpty()){ while(queue1.size()!=1){ queue2.addLast(queue1.pollFirst()); } tmp=queue1.pollFirst(); } if(tmp>0){ System.out.println(tmp+" pop success!"); } else if(tmp==-1){ System.out.println("stack empty!"); } } public void size(){ System.out.println("stack size: "+queue1.size()+queue2.size()); } public static void main(String[] args) throws InterruptedException { queueStack qs=new queueStack(); qs.push(1); qs.pop(); qs.push(2); qs.push(3); qs.push(4); qs.pop(); qs.size(); } }