从头开始创建Stacks toString?

时间:2016-04-06 19:29:43

标签: java stack

我正在从头开始创建一个Stack,并且在创建toString()方法时遇到了困难。我完成了其余的堆栈。我正在创建一个从头开始,因为它是一个任务。如果我能得到一些我做错的提示,那将非常有帮助,谢谢!!

public class MyStack<Type> {
    private Node top;
    private int size;

    private class Node{
        private Node next;
        private Type current;

        public Node() {
            next = null;
            current = null;
        }
    }

    public void push(Type item) {
        Node old = top;
        top = new Node();

        top.current = item;
        top.next = old;

        size++;

    }

    public Type pop() {
        Type type = null;
        if(top != null) {
            type = top.current;
            top = top.next;
            size--;
        }

        return type;
    }

    public Type peek(){
        return top.current;
    }

    public int size() {
        return size;
    }
    public boolean isEmpty(){
        boolean result = false;
        if(size > 0) {
            result = false;
        } else{
            result = true;
        }
        return result;
    }

    public String toString() { // this is where I'm having issues.
        String result = "[";
        if(top != null) {
            while(top.next != null) {
                result = result + top.current;
            }

        }

        result = result + "]";
        return result;
    }
}

1 个答案:

答案 0 :(得分:0)

不要使用top来遍历Stack,List,Queue,Tree或您将实现的任何其他集合。因为你会松散参考这个集合的开头。而是创建临时变量来遍历它。

//toString in MyStack class
public String toString(){
    String s = "";
    Node temp = top;
    while(temp != null){
        s+= temp + " ";
        temp = temp.getNext();
    }
    return s;
}
//toString in Node class
public String toString(){
     return current +"
}

public Node getNext(){
    return next;
}