Home Web Front-end JS Tutorial JavaScript uses recursive method to reverse stack elements

JavaScript uses recursive method to reverse stack elements

Apr 02, 2018 am 09:39 AM

Let’s look at an interview question first. The question is as follows: There is a stack, and the elements 1, 2, 3, 4, 5 are pushed into it at once, and the result is [1, 2, 3, 4 ,5], now we can only use recursive method to reverse the elements in the stack, and the result is [5,4,3,2,1]. If there is no question requirement, this would be relatively simple. You can solve the problem directly with arr.reverse(), but it is interesting to only use recursion. As a novice, I have to study it carefully.

##Hands-on analysis

We regard the stack [1, 2, 3, 4, 5] as consisting of two Partially composed: the top element 1 of the stack and the remaining parts [2, 3, 4, 5].

If we can reverse [2, 3, 4, 5] and turn it into [5, 4, 3, 2], and then put the original top element 1 on the stack at the bottom, then the entire The stack is turned upside down and becomes [5, 4, 3, 2, 1].

Next we need to consider two things: First, how to reverse [2, 3, 4, 5] into [5, 4, 3, 2]. We just think of [2, 3, 4, 5] as consisting of two parts: the top element 2 and the remaining part [3, 4, 5].

We only need to reverse [3, 4, 5] first to become [5, 4, 3], and then put the previous top element 2 at the bottom of the stack, which becomes [5 , 4, 3, 2].

As for how to reverse [3, 4, 5]... Many readers may think that this is recursion. That is, every time you try to invert a stack, the top element of the current stack pops out, then inverts the stack composed of remaining elements, and finally puts the previous top element at the bottom of the stack composed of remaining elements. The condition for the end of recursion is that the remaining stack is empty

show a wave of code

//这个函数的作用是把栈中的元素展开
function reverseStack(arr){ 
  if(
  arr.length != 0
    )
  {
   var topItem = arr.pop() 
   reverseStack(arr) pushStack(arr, topItem) 
   } 
   return arr}//这个函数的作用是把函数进行颠倒
   function pushStack(arr, item){   else{    console.log(arr)
    if(arr.length == 0){
     arr.push(item)
   }
Copy after login

Related recommendations:

Inversion Elements in the stack - inversion of the stack

Invert the stack

Implementation of stack transposition

The above is the detailed content of JavaScript uses recursive method to reverse stack elements. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recursive implementation of C++ functions: Is there a limit to recursion depth? Recursive implementation of C++ functions: Is there a limit to recursion depth? Apr 23, 2024 am 09:30 AM

The recursion depth of C++ functions is limited, and exceeding this limit will result in a stack overflow error. The limit value varies between systems and compilers, but is usually between 1,000 and 10,000. Solutions include: 1. Tail recursion optimization; 2. Tail call; 3. Iterative implementation.

Do C++ lambda expressions support recursion? Do C++ lambda expressions support recursion? Apr 17, 2024 pm 09:06 PM

Yes, C++ Lambda expressions can support recursion by using std::function: Use std::function to capture a reference to a Lambda expression. With a captured reference, a Lambda expression can call itself recursively.

Recursive implementation of C++ functions: Comparative analysis of recursive and non-recursive algorithms? Recursive implementation of C++ functions: Comparative analysis of recursive and non-recursive algorithms? Apr 22, 2024 pm 03:18 PM

The recursive algorithm solves structured problems through function self-calling. The advantage is that it is simple and easy to understand, but the disadvantage is that it is less efficient and may cause stack overflow. The non-recursive algorithm avoids recursion by explicitly managing the stack data structure. The advantage is that it is more efficient and avoids the stack. Overflow, the disadvantage is that the code may be more complex. The choice of recursive or non-recursive depends on the problem and the specific constraints of the implementation.

Detailed explanation of C++ function recursion: application of recursion in string processing Detailed explanation of C++ function recursion: application of recursion in string processing Apr 30, 2024 am 10:30 AM

A recursive function is a technique that calls itself repeatedly to solve a problem in string processing. It requires a termination condition to prevent infinite recursion. Recursion is widely used in operations such as string reversal and palindrome checking.

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

A beginner's guide to C++ recursion: Building foundations and developing intuition A beginner's guide to C++ recursion: Building foundations and developing intuition May 01, 2024 pm 05:36 PM

Recursion is a powerful technique that allows a function to call itself to solve a problem. In C++, a recursive function consists of two key elements: the base case (which determines when the recursion stops) and the recursive call (which breaks the problem into smaller sub-problems ). By understanding the basics and practicing practical examples such as factorial calculations, Fibonacci sequences, and binary tree traversals, you can build your recursive intuition and use it in your code with confidence.

C++ function recursion explained: alternatives to recursion C++ function recursion explained: alternatives to recursion May 01, 2024 pm 04:54 PM

Recursion is a technique where a function calls itself, but has the disadvantages of stack overflow and inefficiency. Alternatives include: tail-recursion optimization, where the compiler optimizes recursive calls into loops; iteration, which uses loops instead of recursion; and coroutines, which allow execution to be paused and resumed, simulating recursive behavior.

C++ Recursion Advanced: Understanding Tail Recursion Optimization and Its Application C++ Recursion Advanced: Understanding Tail Recursion Optimization and Its Application Apr 30, 2024 am 10:45 AM

Tail recursion optimization (TRO) improves the efficiency of certain recursive calls. It converts tail-recursive calls into jump instructions and saves the context state in registers instead of on the stack, thereby eliminating extra calls and return operations to the stack and improving algorithm efficiency. Using TRO, we can optimize tail recursive functions (such as factorial calculations). By replacing the tail recursive call with a goto statement, the compiler will convert the goto jump into TRO and optimize the execution of the recursive algorithm.

See all articles