無法使用 JavaScript 中的 for 迴圈將所有棧元素推入另一個棧?


我們知道,棧遵循後進先出原則。在開始向另一棧插入元素時,你需要從第一個棧中將所有元素彈出 (pop()) 並推 (push) 入第二個棧中。

示例

var myFirstStack=[10,20,30,40,50,60,70];
var mySecondStack=[];
for(;myFirstStack.length;){
   mySecondStack.push(myFirstStack.pop());
}
console.log("After popping the all elements from the first stack=");
console.log(myFirstStack);
console.log("After pushing (inserting) all the elements into the second
stack=");
console.log(mySecondStack);

要執行上述程式,你需要使用以下命令 -

node fileName.js.

此處,我的檔名是 demo189.js。

輸出

它將輸出以下內容 -

PS C:\Users\Amit\javascript-code> node demo189.js
After popping the all elements from the first stack=
[]
After pushing (inserting) all the elements into the second stack=
[
   70, 60, 50, 40,
   30, 20, 10
]

更新日期: 2020 年 9 月 14 日

253 次瀏覽

開啟你的 職業

完成課程即可獲取認證

開始
廣告