首页 > 解决方案 > 为什么当我将一个元素压入堆栈时会得到一个奇怪的结果?

问题描述

我正在使用链表在 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());
    }

}

如果“搜索”方法正确,我还想提示一下。在解决我最初的问题之前,我无法判断它是否有效。

标签: javalinked-liststack

解决方案


推荐阅读