🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
##栈和队列 >1.定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。 ~~~ import java.util.Stack; public class Solution { public Stack<Integer> s=new Stack<Integer>(); public Stack<Integer> m=new Stack<Integer>(); public void push(int node) { s.push(node); if(m.isEmpty()){ m.push(node); }else if(m.peek()>node){ m.push(node); }else{ m.push(m.peek()); } } public void pop() { s.pop(); m.pop(); } public int top() { return s.peek(); } public int min() { return m.peek(); } } ~~~ >2.编写一个类,只能用两个栈结构实现队列,支持队列的基本操作(push,pop)。 给定一个操作序列ope及它的长度n,其中元素为正数代表push操作,为0代表pop操作,保证操作序列合法且一定含pop操作,请返回pop的结果序列。 测试样例: [1,2,3,0,4,0],6 返回:[1,2] ~~~ import java.util.*; public class TwoStack { class Queue{ Stack<Integer> pushs=new Stack<Integer>(); Stack<Integer> pops=new Stack<Integer>(); public void push(int i){ while(!pops.isEmpty()){ pushs.push(pops.pop()); } pushs.push(i); } public int pop(){ while(!pushs.isEmpty()){ pops.push(pushs.pop()); } return pops.pop(); } public boolean isEmpty(){ return pushs.isEmpty()&&pops.isEmpty(); } } public int[] twoStack(int[] ope, int n) { // write code here if(ope.length<2) return ope; Queue q=new Queue(); ArrayList<Integer> a=new ArrayList<Integer>(); for(int i=0;i<ope.length;++i){ if(ope[i]!=0){ q.push(ope[i]); }else{ a.add(q.pop()); } } Object[] arr=a.toArray(); int[] res=new int[arr.length]; for(int i=0;i<arr.length;++i){ res[i]=(int)arr[i]; } return res; } } ~~~ >3.实现一个栈的逆序,但是只能用递归函数和这个栈本身的pop操作来实现,而不能自己申请另外的数据结构。 给定一个整数数组A即为给定的栈,同时给定它的大小n,请返回逆序后的栈。 测试样例: [4,3,2,1],4 返回:[1,2,3,4] ~~~ import java.util.*; public class StackReverse { public int[] reverseStack(int[] A, int n) { // write code here if(A==null) return null; for(int i=0;i<n/2;i++){ int tmp = A[i]; A[i] = A[n-1-i]; A[n-1-i] = tmp; } return A; } private int get(Stack<Integer> stack){ int result = stack.pop(); if(stack.empty()){ return result; }else{ int last = get(stack); stack.push(result); return last; } } private void reverse(Stack<Integer>stack){ if(stack.empty()) return ; int i = get(stack); reverse(stack); stack.push(i); } } ~~~