)私はコンパイルするためにコードを取得しましたが、ユーザーの入力を受け取り、push()メソッドを使って文字列をスタックに追加します。次に、他の方法を使用して入力の順序を逆にします。たとえば、ユーザーがいくつかの文字列を入力します。 "Hello" "World" "!" そして、ユーザが入力として "end"と入力すると、プログラムはスタックへのプッシュを止め、逆の順序で印刷します: "!" 「世界」 「こんにちは」ここスタックを使用して逆順で文字列を出力するのを助ける必要があります(詳細は
は、以下の私のコードです:
public class stackReversal {
private Node first = null;
private class Node {
private String item;
private Node next;
}
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 String toString() {
StringBuilder nodes = new StringBuilder();
Node node = first;
while (node != null) {
nodes.append(node.item);
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();
Scanner input = new Scanner(System.in);
System.out.print("Enter strings:");
String in = input.nextLine();
while (!in.equals("end-of-input")) {
s.push(in);
if (in.equals("end"))
break;
}
System.out.println("Strings:" + s);
}
}
私たちがコンパイルとテストをするためのオーバーヘッド、コードとコードを書式化して行単位で表示するためのオーバーヘッドを追加してください。 –
プラス:私たちがあなたを助けるために時間を費やしたい。したがって、ソースコードを適切に書式設定/インデントするのに数分を費やすのに十分なほど丁寧でなければなりません。あなたは知っています:可読性**事項**! – GhostCat