如果C是一个堆栈,我试图弄清楚输出System.out.println(str);
将是什么。
我相信System.out.println(str);
命令会输出Harry
,但是我想确认一下,因为我不完全理解该.remove()
命令。当我将此伪代码转换为Java时,.remove()
除非我将整数传递给该命令,否则它将无法识别该命令.remove(2)
。因此,在这种情况下,我不确定是否.remove()
是无效命令,或者它是否是适用于Stack的方法。我的研究似乎表明,没有适用于堆栈的.remove()方法。
所以我的问题是,如果C是一个堆栈,将输出System.out.println(str);
什么?
public interface Container<T>
{
void insert(T x); // insert x into Container
T remove(); // remove item from Container
}
public class C<T> implements Container<T>
{
public C() { /* constructor */ }
public void insert(T x) { /* insert x into C */ }
public T remove() { /* remove item from C */ }
//.. other methods
}
Here is a program segment that uses class C above:
Container<String> words = new C<String>();
String w1 = "Tom";
String w2 = "Dick";
String w3 = "Harry";
String w4 = "Moe";
words.insert(w1);
words.insert(w2);
words.insert(w3);
words.insert(w4);
String str = words.remove(); // remove
str = words.remove(); // remove again
System.out.println(str);
如果C
是常规堆栈(并且编码正确),则它是LIFO(后进先出)容器。
这意味着事物将以与放置它们相反的顺序出现。
所以第一个remove
给你Moe
,第二个给你Harry
。
详细说明:
operation stack (top,...,bottom) str
--------- ---------------------- ---
initial state <empty>
push tom tom
push dick dick, tom
push harry harry, dick, tom
push moe moe, harry, dick, tom
pop str harry, dick, tom moe
pop str dick, tom harry
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句