用JAVA实现堆栈(数组篇)

什么是堆栈,关于这个名词,我在百度,google搜索了半天,也没有发现一个比较权威的解释,还有许多资料语焉不详,就以维基百科的解释为准吧,和我记忆中的一致。

堆栈(英文:stack),中国大陆作堆栈,台湾作堆叠,在计算机科學中,是一種特殊的串列形式的資料結構,它的特殊之處在於只能允許在鏈結串列或陣列的一端(稱為堆疊頂端指標,英文為top)進行加入資料(push)和輸出資料(pop)的運算。另外堆疊也可以用一維陣列或連結串列的形式來完成。堆疊的另外一個相對的操作方式稱為佇列。
由於堆疊資料結構只允許在一端進行操作,因而按照後進先出(LIFO, Last In First Out)的原理運作。

堆疊資料結構使用兩種基本操作:推入(push)和彈出(pop):
推入(push) :將數據放入堆疊的頂端(陣列形式或串列形式),堆疊頂端top指標加一。
彈出(pop) :將頂端數據資料輸出(回傳),堆疊頂端資料減一。

下面是用java数组实现堆栈

/** * 使用数组实现堆栈,包括入栈、出栈、获取堆栈长度、 * @author Adair */ public class Stack { Object[] data; int maxSize; //栈顶位置 int top; public Stack(int maxSize) { this.maxSize = maxSize; data = new Object[maxSize]; top = -1; } /** * 获取堆栈长度 * @return 堆栈长度 */ public int getSize() { return maxSize; } /** * 返回栈中元素的个数 * @return 栈中元素的个数 */ public int getElementCount() { return top; } /** * 判断栈空 * @return 栈空 */ public boolean isEmpty() { return top == -1; } /** * 判断栈满 * @return 栈满 */ public boolean isFull() { return top+1 == maxSize; } /** * 依次加入数据 * @param data 要加入的数据通信 * @return 添加是否成功 */ public boolean push(Object data) { if(isFull()) { System.out.println("栈已满!"); return false; } this.data[++top] = data; return true; } /** * 从栈中取出数据 * @return 取出的数据 */ public Object pop() throws Exception{ if(isEmpty()) { throw new Exception("栈已空!"); } return this.data[top--]; } /** * 返回栈顶元素 * @return */ public Object peek() { return this.data[getElementCount()]; } public static void main(String[] args) throws Exception { Stack stack=new Stack(1000); stack.push(new String("1")); stack.push(new String("2")); stack.push(new String("3")); stack.push(new String("4")); stack.push(new String("5")); System.out.println(stack.peek()); while(stack.top>=0) { System.out.println(stack.pop()); } } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值