Search code examples
indexinglinked-listreversetostring

toString reverse order in java


My method toString() is supposed to return a string representation of the stack. The string representation consists of the stacks's elements in the order they are stored, enclosed in square brackets. My problem is that I am now returning [element0, element1, element2, element3, element4] so I wonder if there is there a simple way to return the string in reverse order i.e. to return [element4, element3, element2, element1, element0] instead?

public class Stack<E> implements IStack<E> {
    public String toString() {
    String str = "[";
    if (head != null) {
        str += head.getmElement();
        Node<E> tempNode = head.getmNextNode();
        while (tempNode !=  null) {
            str += ", " + tempNode.getmElement();
            tempNode = tempNode.getmNextNode();
        }
    }
    str += "]";
    return str; }

Node class:

public class Node<E> {
private E mElement;
private Node<E> mNextNode;

Node(E data) {

    this.setmElement(data);
}
public E getmElement() {
    return this.mElement;
}
public void setmElement(E element) {
    this.mElement = element;
}
public Node<E> getmNextNode()
{
    return this.mNextNode;
}
public void setmNextNode(Node<E> node)
{
    this.mNextNode = node;
}}

Solution

  • You could use a StringBuilder and insert every element at the beginning instead of appending it:

    public String toString() {
        StringBuilder sb = new StringBuilder("[");
        if (head != null) {
            sb.append(head.getmElement());
            Node<E> tempNode = head.getmNextNode();
            while (tempNode !=  null) {
                sb.insert(1, ", ").inser(1, tempNode.getmElement());
                tempNode = tempNode.getmNextNode();
            }
        }
        sb.append("]");
        return sb.toString();
    }