【发布时间】:2021-03-03 09:45:06
【问题描述】:
给定一个完整的句子,是否可以在不反转单词本身的情况下反转堆栈。 IE。 第一句话——玛丽有一只小羊羔。它的羊毛像雪一样白。 新句子——Lamb little a had mary。雪白如绒。 基本上卡在循环部分。出于某种原因,我让它显示单词并在期间中断,但是对于我的生活,我似乎无法让 push/pop args 做我想让他们做的事情。我把所有的 cmets 都放在了,因为它可以帮助我在编码休息时理清思路,就像我现在在我的电脑前摔倒之前所做的那样。
public class ReverseTheStack
{
private static LinkedList<Object> list = new LinkedList<Object>();
public static class Stack
{
public void push(Object obj)
{
list .addFirst(obj);
}
public Object pop()
{
return list.removeFirst();
}
}
public static void main(String [] args)
{
//First hard code the sentence for testing
String sentence = "Mary had a little lamb. Its fleece was white as snow.";
//The scanner is created with the String obj inside it
Scanner in = new Scanner(sentence);
//Set the scanner's delimiter to a period and the space after: "\\. "
in.useDelimiter(" ");
//Create a stack
Stack sentenceReversal = new Stack();
while(in.hasNext())
{
sentenceReversal.push(in.next());
if(in.toString().contains("\\."))
{
System.out.println(sentenceReversal.pop());
}
}
//Close the scanner
in.close();
}
}
【问题讨论】:
-
你不想把所有东西都推上去,然后在最后全部弹出吗?那不是你的代码所做的......为什么
liststatic ?