用一个栈排序另外一个栈
用一个栈排序另外一个栈,使得栈变为有序,只能使用一个辅助栈和变量,不能使用其他数据结构。
代码实现
- /**
- * 排序栈
- * @param {*} stack 待排序的栈
- * @returns 排序后的栈
- */
- function stackSort(stack) {
- const help = [];
- while (stack.length) {
- const cur = stack.pop();
- // 如果新栈为空,或者当前元素小于栈顶元素,将当前元素加入栈中
- if (help.length === 0 || help[help.length - 1] < cur) {
- help.push(cur);
- } else {
- //如果help栈顶元素大于当前元素,将help所有的大于当前元素的数据出栈存入stack中
- while (help[help.length - 1] > cur) {
- stack.push(help.pop());
- }
- help.push(cur);
- }
- }
- return help;
- }
- // test
- console.log(stackSort([2, 1, 3, 5, 4, -2]));
- // [ -2, 1, 2, 3, 4, 5 ]
JavaScript