给出一个完整的句子,是否有可能在不反转单词本身的情况下反转堆栈。i、 玛丽有一只小羊羔。它的羊毛像雪一样白。新句子-小羊有玛丽。雪如白雪被它的羊毛所覆盖。基本上卡在环部分。出于某种原因,我让它显示单词和句号,但就我的一生而言,我似乎无法让push/pop参数做我想让他们做的事情。我把所有的意见,因为它可以帮助我得到我的思想秩序,当我休息时,从编码像我会做的,现在我打破我的头在我的电脑上。
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();
}
}
1条答案
按热度按时间62o28rlo1#
可以使用
Stack
自Java1.0以来就存在的实现(尽管即使提到的javadoc页面也建议使用Deque
接口及其实现(提供更丰富的后进先出操作集):输出: