Question

If you look at my toString() method below, you can see that I have not finished it. I don't know how? Can anyone explain how I might proceed? Confused :-| I'm new to linked lists and so I automatically went for the Arrays.toString() approach before I realized that there is, of course, no arrays anywhere.

import java.util.Arrays;


public class LinkedIntegerStack {

private Node top = null;
private int size = 0;

public int size(){
    return size;
}

public boolean isEmpty() {
    if(top == null){
        return true;
    }
    else{
        return false;
    }
}

public void push(int value) {
    Node n = new Node(value);
    n.next = top;
    top = n;
    size++;
}

public int top(){ //just returns a value..doesn't change structure

    return top.element;
}

public int pop(){
    if (isEmpty()){
        throw new StackEmptyException();
    }
    int toReturn = top.element;
    top = top.next;
    size--;

    return toReturn;
}       

public String toString() {
    return "[ Top = " + size +"]" + "[Stack = " );
}

private class Node {
    int element;
    Node next;

    public Node(int value){
        element = value;
    }
}

public static void main(String[] args) throws StackEmptyException{

    LinkedIntegerStack stack = new LinkedIntegerStack();

    stack.push(17);
    System.out.println(stack);

    stack.push(11);
    System.out.println(stack);

    try{
            stack.pop();
            System.out.println(stack);
        }
    catch(StackEmptyException ex){
            System.out.print("Stack is Empty: Error");
        }
    System.out.println("Stack: " + stack);
}

}

Was it helpful?

Solution

The solution is pretty easy.

It should be enough to iterate through the stack.

public String toString() {
    String result = "[ Top = " + size +"]" + "[Stack = [";

    if (top == null) {
        return result + "]]";

    Node temp = top;
    while (temp != null) {
        result += temp + ', '
        temp = temp.next;
    }

    return result += temp.element + "]]";
}

Of course you should add at least getter methods to Node class, i.e. getElement() and getNext();

PS: the code isn't tested, but it should be fine.

OTHER TIPS

System.out.println(Arrays.toString(stack.toArray()));

From https://stackoverflow.com/a/395403/2736496

JavaDoc: Arrays.toString(o[]), Collection.toArray(cll)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top