package com.tw.dst.sq; /** * * <p>栈算法:栈是一种后进先出的方式</p> * @author tangw 2010-11-26 */ public class Stack { //栈数组 long stackArr[]; //栈的大小 int maxSize; //栈的顶部 int top; //初始化一个大小为size的栈 public Stack(int size){ maxSize = size; stackArr = new long[size]; top = -1; } //出栈操作 public long pop(){ return stackArr[top--]; } //进栈操作 public void push(long value){ stackArr[++top] = value; } //判断栈是否为空 public boolean isEmpty(){ return top == -1; } //判断栈是否已满 public boolean isFull(){ return top == maxSize-1; } //取栈顶元素 public long peek(){ return stackArr[top]; } public static void main(String[] args) { Stack stack = new Stack(10); System.out.println("----插入数据----"); while(!stack.isFull()){ long v = (long) (Math.random()*100); stack.push(v); System.out.print(v+" "); } System.out.println("----取出数据----"); while(!stack.isEmpty()){ long topValue = stack.pop(); System.out.print(topValue+" "); } } }
posted on 2010-11-27 15:19 大米文子 阅读(166) 评论(0) 编辑 收藏 举报