2015-11-17 39 views
0

如果C是一个堆栈,我想知道System.out.println(str);的输出是什么。这个伪代码的输出是什么?

我认为System.out.println(str);命令会输出Harry,但我想确认,因为我不完全理解.remove()命令。当我将这个伪代码转换为Java时,它不会识别.remove()命令,除非我通过一个整数,例如.remove(2)。所以我不确定在这种情况下,如果.remove()是一个无效的命令,或者它是一个适当的堆栈方法。我的研究似乎表明,没有适用于堆栈的.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); 
+0

为什么向下票呢? –

+0

可能是因为有大量的堆栈实现可以从中看到正确的行为。你似乎正在使用一个基于JVM的应用程序,它只有这样一个[实现](http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html) – paulpdaniels

回答

1

如果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