Question: You are given a stack and you have to reverse it, using only stack operations push and pop. The algorithm for the above problem can be given in this way:- First POP all elements of the stack till it becomes empty Now for each upward step in the recursion, push the elements at the bottom of the stack.
Stack
Algorithms involving stacks
-
-
Suppose we want to find the minimum element available in a stack at any point of time. The most trivial and common method would be to traverse the entire stack and keep a record of the least element encountered. At the end, we can return this element. This method no doubt is easy, but it consists of traversing the entire stack again and again, which can lead to time complexities. Thus, we need to optimize it, and it can be done with a very neat little trick:- ALGORITHM:- Take an…
-
Post-fix expressions have a very special place in computer science. Most of the computations are performed using stacks. In-fact a very simple calculator works on the principle of post-fix evaluation to get the answer. A post-fix notation is also known as the reverse Polish notation. The steps involved in evaluating a post-fix expression can be defined as follows. We use the concept of stacks to evaluate the same. ALGORITHM: Scan the post-fix string from left to right. Initialize an empty stack. Repeat the below steps 4 and 5 till all…
-
Misc
Write an Algorithm to convert an INFIX expression to a POSTFIX expression?
by nikoo282 minutes readIn infix expressions, the operator precedence is implicit unless we use parentheses. Therefore, for the infix to postfix conversion algorithm, we have to define the operator precedence inside the algorithm. We did this in the post covering infix, postfix and prefix expressions. What are infix, prefix and postfix expressions? Important properties:- Let us consider the infix expression 2 + 3 * 4 and its postfix will be 2 3 4 * +. Notice that between infix and postfix the order of the numbers(or operands) is unchanged. It is 2 3…
-
Stacks can be used to check if the given expression has balanced symbols or not. The algorithm is very much useful in compilers. Each time parser reads one character at a time. If the character is an opening delimiter like ‘(‘ , ‘{‘ or ‘[‘ then it is PUSHED in to the stack. When a closing delimiter is encountered like ‘)’ , ‘}’ or ‘]’ is encountered, the stack is popped. The opening and closing delimiter are then compared. If they match, the parsing of the string continues. If they…
-
A stack is a linear data structure that maintains the order in which elements are added. It only has one point to add and remove data.
- 1
- 2