62,628
社区成员
发帖
与我相关
我的任务
分享package com.saturday.test;
/**
* 实现堆栈操作
* @author 王建波
*/
public class MyStack {
private int index;
private int[] stack;
private int[] max;
private static int PAGE_SIZE=10;
public static void main(String[] args){
MyStack stack=new MyStack();
try{
//入栈出栈测试
stack.push(1);
stack.push(2);
stack.push(12);
stack.push(17);
stack.push(55);
stack.push(19);
System.out.println(
stack.toString()+"max:"+stack.getMax()
);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(
stack.toString()+"max:"+stack.getMax()
);
stack.pop();
stack.pop();
stack.pop();
//测试自动扩容
stack.push(0);
stack.push(110);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(6);
stack.push(7);
stack.push(8);
stack.push(9);
stack.push(10);
stack.push(11);
stack.push(12);
stack.push(13);
System.out.println(stack);
System.out.println(stack.getMax());
}catch (Exception e) {
e.printStackTrace();
}
}
public MyStack(){
index=-1;
stack=new int[PAGE_SIZE];
max=new int[PAGE_SIZE];
}
public void push(int num){
int stackLen=stack.length;
index++;
stack[index]=num;
max[index]=index<1?num
:(max[index-1]>num?max[index-1]:num);
if(index==stackLen-1){
int[] _newStack=new int[stackLen+PAGE_SIZE];
int[] _newMax=new int[stackLen+PAGE_SIZE];
System.arraycopy(stack,0,_newStack,0,stackLen);
System.arraycopy(max,0,_newMax,0,stackLen);
stack=_newStack;
max=_newMax;
}
}
public int pop() throws Exception{
if(index>=0){
return stack[index--];
}else {
throw new Exception("Emputy Stack!");
}
}
public int getValue() throws Exception{
if(index>=0){
return stack[index];
}else {
throw new Exception("Emputy Stack!");
}
}
public int getMax() throws Exception{
if(index>=0){
return max[index];
}else {
throw new Exception("Emputy Stack!");
}
}
public String toString(){
StringBuffer sbOut=new StringBuffer();
sbOut.append('[');
for(int i=0;i<=index;i++){
sbOut.append(i==0?stack[i]:","+stack[i]);
}
sbOut.append(']');
return sbOut.toString();
}
}