2017-06-20 91 views
1
1.theStack.push(1); 
2.theStack.push(2); 
3.theStack.push(3); 
4.theStack.push(theStack.pop()); 
5.theStack.push(theStack.pop() +theStack.pop()); 
6.theStack.push(6); 
7.theStack.push(7); 
8.theStack.push(theStack.pop() * theStack.pop()); 

當第一3行執行輸出將是數據結構:堆棧

|3| 
|2| 
|1| 

我有一個問題理解上述線。任何人都可以請解釋上面的行。第4-8行會發生什麼?

+2

他們迷失在您未發佈的代碼中。請閱讀[mcve]和[問]。 – Yunnosch

+0

你確定這是'popO'而不是'pop()'嗎? (如果你不確定...)類似於':'。 –

+0

爲什麼標記爲C? –

回答

3

假設pop0是一個錯字,它應該是對pop()的調用,它將刪除您推入堆棧並返回它的最後一個元素。讓我們按照該程序:

theStack.push(1); 
// 1 is pushed to the stack. The stack now contains [1] 

theStack.push(2); 
// 2 is pushed to the stack. The stack now contains [2, 1] 

theStack.push(3); 
// 3 is pushed to the stack. The stack now contains [3, 2, 1] 

theStack.push(theStack.pop()); 
// 3 is popped, and then pushed back in, so the stack still contains [3, 2, 1] 

theStack.push(theStack.pop() + theStack.pop()); 
// 3 and 2 are popped, added, and pushed back in, so the stack now contains 
// [5, 1] 

theStack.push(6); 
// 6 is pushed to the stack. The stack now contains [6, 5, 1] 

theStack.push(7); 
// 7 is pushed to the stack. The stack now contains [7, 6, 5, 1] 

theStack.push(theStack.pop() * theStack.pop()); 
// 7 and 6 are popped, multiplied, and pushed back in, so the stack now contains 
// [42, 5, 1] 
+0

嗨Mureinik theStack。 push(theStack.pop()+ theStack.pop()); // 3和2被彈出,添加並推回,所以現在的堆棧 包含 // [5,1](你是如何得到值5的) – Eranka

+0

@Eranka 3 + 2 = 5 :-) – Mureinik