如果你有一个堆栈的例子
2 48 1 的 32 24 12 60 的
然后在操作后它应该看起来像
2 48 60 的 32 24 12 1 的
答案 0 :(得分:3)
这是解决方案的JS实现。
var myStack = [ 2, 48, 1, 32, 24, 12, 60 ];
var posMax = 0;
var maxValue = myStack[0];
var posMin = 0;
var minValue = myStack[0];
var tempStack = [ ]; // will be constructed, but in the reverse order.
var counter = 0;
do {
var tempElement = myStack.pop();
if(tempElement > maxValue) {
posMax = counter;
maxValue = tempElement;
}
if(tempElement < minValue) {
posMin = counter;
minValue = tempElement;
}
tempStack.push(tempElement);
counter++;
} while(myStack.length != 0);
// Reverse the order of the temp Stack
var tempStack2 = [];
do {
tempStack2.push(tempStack.pop());
} while (tempStack.length != 0)
tempStack = tempStack2;
// Constructing the returned Stack.
var newStack = [];
counter = 0;
do
{
var tempElement = tempStack.pop();
if(counter !== posMin && counter !== posMax) {
newStack.push(tempElement);
}
if(counter === posMax) {
newStack.push(minValue);
}
if(counter === posMin) {
newStack.push(maxValue);
}
counter++;
} while(tempStack.length != 0);
// Reverse the order of the new Stack
var result = [];
do {
result.push(newStack.pop());
} while (newStack.length != 0);
console.log("Final:" + result);
答案 1 :(得分:3)
这是一个更好的Javascript实现:
var stack = [2, 48, 1, 32, 24, 12, 60];
var minPos = stack.indexOf(stack.reduce(function (a, b) { return a <= b ? a : b; }));
var maxPos = stack.indexOf(stack.reduce(function (a, b) { return a >= b ? a : b; }));
stack[minPos] = stack.splice(maxPos, 1, stack[minPos])[0];
除了设置示例堆栈的行之外,这种方法还可以做三件事: