##棧和隊列
>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);
}
}
~~~