发布于2020-11-19 20:33 阅读(1238) 评论(0) 点赞(30) 收藏(5)
package com.javase.advanced.work02;
/* 1.栈可以存储java中任何引用类型的数据
2.提供push方法压栈(栈满
3.提供pop方法弹栈(栈空
4.编写测试程序,new栈对象,调用push pop方法模拟压栈弹栈动作
5.默认初始化容量是10(无参数
*/
public class Stack {
//Object 父类 可以存储任何引用类型
private Object[] elements;
private int index;
public Stack() {
this.elements = new Object[10];
this.index = -1;
}
public Object[] getElements() {
return elements;
}
public void setElements(Object[] elements) {
this.elements = elements;
}
public void push(Object o) {
if (index >= elements.length - 1) {
System.out.println("栈满,压栈失败");
return;
}
/*思维?
elements[index + 1] = o;
index++;
*/
elements[++index] = o;
System.out.println("压栈" + o + "成功,栈帧指向" + index);
}
public void pop() {
if (index < 0) {
System.out.println("栈空,弹栈失败");
return;
}
System.out.print("弹栈" + elements[index] + "元素成功,");
elements[index--] = null;//思考?
//index--;
System.out.println("栈帧指向" + index);
}
public void traversal() {
for (int i = 0; i <= elements.length - 1; i++) {
System.out.print(elements[i] + " ");
}
System.out.println();
}
}
//还是开始没思路,读答案一半才写出来
```java
ackage com.javase.advanced.work02;
public class Test01 {
public static void main(String[] args) {
Stack stack = new Stack();
stack.pop();
stack.pop();
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.pop();
stack.pop();
stack.traversal();
//System.out.println(stack.getElements());
// String[] array = {"1", "2", "3", "4", "7"};
// stack.setElements(array);
}
}
原文链接:https://blog.csdn.net/weixin_51891578/article/details/109784766
作者:java之恋
链接:http://www.javaheidong.com/blog/article/1034/d41ad88df232939e5e1a/
来源:java黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!