java - 为什么当我将一个元素压入堆栈时会得到一个奇怪的结果?
问题描述
我正在使用链表在 Java 中实现堆栈,但我仍然是编程的初学者。
我想将一个元素推入堆栈,但我得到了这个结果,我该如何解决它:
“ Stack@15db9742 ”
这是我的代码:
public class Stack {
class Element{
int data;
Element next = null;
Element(int value){
data = value;
next = null;
}
}
private Element head = null;
public Stack() {
head = null;
}
public boolean isEmpty() {
return this.head == null;
}
public void push(int value) {
Element tmp = new Element(value);
tmp.next = head;
head = tmp;
}
public void pop() {
if(isEmpty())
System.exit(1);
head = head.next;
}
public int stackTop() {
if(isEmpty())
System.exit(2);
return head.data;
}
@Override
public String toString() {
return "Stack [head=" + head + "]";
}
public void makeEmpty() {
}
public int search(int value) {
if(isEmpty())
return -1;
Element cur = head; // cur = cursor
int n = 0;
while(cur != null) {
if(cur.data == value)
return n;
cur = cur.next;
n++;
}
return n;
}
public static void main(String[] args) {
Stack s1 = new Stack();
s1.push(1);
s1.push(2);
s1.push(3);
s1.push(4);
s1.push(5);
System.out.println(s1.toString());
}
}
如果“搜索”方法正确,我还想提示一下。在解决我最初的问题之前,我无法判断它是否有效。
解决方案
推荐阅读
- javascript - 使用 js reduce() 创建键值对并创建一个数组作为值
- c# - 使用 SelectListItem 设置 DropDownList 的选定值
- angular5 - 如何在 ng2-chart 条形图中删除条形顶部的百分比计算
- php - 在 Laravel API 中重用重置密码
- oauth-2.0 - REST API 上的 OAuth 2.0 与第三方提供商
- azure - 通过 ARM 模板将证书应用于 ASE ILB 失败
- regex - 如何在 spark hive 中应用带有 unicode 字符的 regexp_replace
- firebase - 浏览 Firebase Firestore 中的读取配额
- php - 在 IIS 重新启动之前,使用 PHP exec 无头运行 Google Chrome 不会返回输出
- sql - 如何使用参数更快地进行 sql 查询?