java实现顺序栈
package sequencestack; /** * Created by Administrator on 2019/4/19. */ public class SequenceStack { private static int STACK_INIT_SIZE = 5; private static int INCREMENT = 1; private Object[] stack; public void initStack(){ stack = new Object[STACK_INIT_SIZE]; } public void push(Object o){ Object[] temp = new Object[stack.length+1]; System.arraycopy(stack,0,temp,0,stack.length); temp[stack.length] = o; stack = temp; } public void pop(){ if(stack.length>STACK_INIT_SIZE){ System.out.println("出栈元素:"+stack[stack.length-1]); Object[] temp = new Object[stack.length-1]; System.arraycopy(stack,0,temp,0,stack.length-1); stack = temp; }else{ System.out.println("当前栈为空"); } } public void print(){ for(int i = stack.length-1;i>=0;i--){ if(i>=STACK_INIT_SIZE){ System.out.println(stack[i]); } } } }
测试
public static void main(String[] args){ SequenceStack sequenceStack = new SequenceStack(); sequenceStack.initStack(); sequenceStack.push(1); sequenceStack.push(2); sequenceStack.push(3); sequenceStack.print(); sequenceStack.pop(); sequenceStack.print(); sequenceStack.pop(); sequenceStack.print(); sequenceStack.pop(); sequenceStack.print(); sequenceStack.pop(); sequenceStack.print(); }
posted on 2019-04-19 16:53 Wll_Knight 阅读(317) 评论(0) 编辑 收藏 举报