使用javascript对堆栈元素进行排序 [英] sorting elements of stack using javascript

查看:66
本文介绍了使用javascript对堆栈元素进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解使用中给出的递归对堆栈元素进行排序 http://www.geeksforgeeks.org/sort-a-stack-using -递归/ 不允许使用while,for..etc之类的任何循环结构.我们只能在Stack S上使用以下ADT函数:

I m trying to understand sorting a stack elements using recursion given in http://www.geeksforgeeks.org/sort-a-stack-using-recursion/ Use of any loop constructs like while, for..etc is not allowed. We can only use the following ADT functions on Stack S:

is_empty(S):测试堆栈是否为空.

is_empty(S) : Tests whether stack is empty or not.

push(S):将新元素添加到堆栈中.

push(S) : Adds new element to the stack.

pop(S):从堆栈中删除顶部元素.

pop(S) : Removes top element from the stack.

top(S):返回top元素的值.请注意, 函数不会从堆栈中删除元素. 我在下面尝试过但出现错误

top(S) : Returns value of the top element. Note that this function does not remove element from the stack. I tried below but getting error

var stack = [-3, 14, 18, -5, 30];

function sortStack() {
  if (stack.length > 0) {
    temp = stack.pop();
    sortStack();
    sortedInsert(temp, stack);
  }
}

function sortedInsert(element, stack) {
  if (stack.length > 0 || element > stack[stack.length - 1]) {
    stack.push(element);
  } else {
    temp = stack.pop();
    sortedInsert(element, stack);
    stack.push(temp);
  }

}

sortStack();

console.log(stack);

RangeError: Maximum call stack size exceeded
at sortedInsert:12:22
at sortedInsert:21:5
at sortedInsert:21:5
at sortedInsert:21:5
at sortedInsert:21:5
at sortedInsert:21:5

推荐答案

使用javascript,需要将局部(作用域)变量声明为var,否则它们是静态的.在sortStack()中t之前没有var的情况下,t将是静态的,并且每次弹出都会被覆盖,在sortStack()的所有返回值上保留t == -3. x在sortedInsert()中也会发生同样的问题.

With javascript, local (scoped) variables need to be declared as var, otherwise they are static. Without the var before t in sortStack(), t would be a static and just get overwritten with each pop, leaving t == -3 on all the returns from sortStack(). The same issue occurs with x in sortedInsert().

var stack = [-3, 14, 18, -5, 30];

function sortStack(s) {
  if (s.length > 0) {
    var t = s.pop();
    sortStack(s);
    sortedInsert(s, t);
  }
}

function sortedInsert(s, e) {
  if (s.length == 0 || e > s[s.length - 1]) {
    s.push(e);
  } else {
    var x = s.pop();
    sortedInsert(s, e);
    s.push(x);
  }
}

sortStack(stack);

console.log(stack);

这篇关于使用javascript对堆栈元素进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆