我需要帮助来编写一个程序,该程序从用户获取输入并使用堆栈进行反转?

时间:2016-11-08 09:16:38

标签: java stack

我正在尝试构建一个程序(Java),它将来自用户的字符串输入放入堆栈,然后使用push和pop反转堆栈。当用户输入“end-line”时,程序将停止推送到堆栈并以相反的顺序打印用户输入的字符串?

public class stackReversal{

private class Node{

    private String item;
    private Node next;
}
private Node first = null;

public boolean isEmpty(){
  return(first == null);
}
public void push(String s){
    Node node = new Node();
    node.item = s;
    node.next = first;

    first = node;
}
public String pop(){
    if(first == null)
       throw new RuntimeException("Stack Empty!");
    String result = first.item;
    first = first.next;
    return result;

}

public String popString(){
    String result="";
    Node current = first;

    while(current != null){
        result += current.item;
        current = current.next;
    }
    return result;
}
public static void main(String [] args)
{
    stackReversal s = new stackReversal();
    s.push("Hello");
    s.push("world");
    s.push("!");
    System.out.println("Strings:" + s);
}
}

1 个答案:

答案 0 :(得分:1)

请找到以下代码。我所做的就是覆盖toString方法来打印节点项。

现在我输入1,2,3它将打印字符串:3 - > 2 - > 1作为输出..希望这有帮助

public class stackReversal {

private class Node {    
    private String item;
    private Node next;
}

private Node first = null;

public boolean isEmpty() {
    return (first == null);
}

public void push(String s) {
    Node node = new Node();
    node.item = s;
    node.next = first;

    first = node;
}

public String pop() {
    if (first == null)
        throw new RuntimeException("Stack Empty!");
    String result = first.item;
    first = first.next;
    return result;

}

public String popString() {
    String result = "";
    Node current = first;

    while (current != null) {
        result += current.item;
        current = current.next;
    }
    return result;
}

/*
 * (non-Javadoc)
 * 
 * @see java.lang.Object#toString()
 * 
 * This method prints the nodes in reerse order
 */
@Override
public String toString() {

    StringBuilder nodes = new StringBuilder();

    Node node = first;

    while (node != null) {
        nodes.append(node.item).append(" -> ");
        node = node.next;
    }

  if(isEmpty()) {
        return "";
    } else {
        return nodes.toString().substring(0, nodes.toString().length() - 4);    
    }
}

public static void main(String[] args) {
    stackReversal s = new stackReversal();
    s.push("1");
    s.push("2");
    s.push("3");
    System.out.println("Strings:" + s);
}

}

相关问题