gpt4 book ai didi

java - 我需要帮助来编写一个程序,该程序接受用户的输入并使用堆栈进行反转?

转载 作者:行者123 更新时间:2023-12-01 09:16:55 25 4
gpt4 key购买 nike

我正在尝试构建一个程序(Java),该程序将从用户输入的字符串放入堆栈中,然后使用入栈和出栈反转堆栈。当用户输入“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);
}
}

最佳答案

请找到下面的代码。我所做的只是重写 toString 方法来打印节点项。

现在我输入 1,2,3 它将打印 Strings: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);
}

}

关于java - 我需要帮助来编写一个程序,该程序接受用户的输入并使用堆栈进行反转?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40483027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com