栈-数组模拟栈

package c_stack.A_array;


/**
 * 数组模拟栈
 * push:top+1,然后在top+1索引对应的位置上添加值
 * pop:返回top对应的值,然后top-1
 * 常见错误,栈没值,返回值,
 * 栈满,添加值
 * 
 * @author Administrator
 *
 */
public class Array_stack {
private int maxSize;
private long[] stackArray;
private int top;


/*
* 初始化数组大小,和栈顶值
*/
public Array_stack(int s) {
maxSize = s;
stackArray = new long[maxSize];
top = -1;
}


/*
* 入栈
*/
public void push(long j) {
stackArray[++top] = j;
}


/*
* 出栈
*/
public long pop() {
return stackArray[top--];

}
/*
* 查看
*/
public long peek(){
return stackArray[top];
}
/*
* 查看是否为空
*/
public boolean isEmpty(){
return (top==-1);
}
/*
* 栈是否充满
*/
public boolean isFull(){
return (top==maxSize-1);
}
}

package c_stack.A_array;


class StackApp {
public static void main(String[] args) {
Array_stack theStack = new Array_stack(10); // make new stack
theStack.push(20); // push items onto stack
theStack.push(40);
theStack.push(60);
theStack.push(80);


while (!theStack.isEmpty()) // until it's empty,
{ // delete item from stack
long value = theStack.pop();
System.out.print(value); // display it
System.out.print(" ");
} // end while
System.out.println("");
} // end main()
} // end class StackApp

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值