Note : Assuming the stack can grow dynamically we are not considering the overflow condition.
Lets see an example of an stack class using array in Java script:-
As you can see the above definition we have created a skeleton of a stack class which contains a constructor in which we declare an array to implement stack. Hence, with the creation of an object of a stack class this constructor would be called automatically.
Now let’s see implementation of each method:
- Push: Adds an element to the stack
// push function
// push element into the items
This method adds an element at the top of the stack.
- Pop() : Removes an element from the stack, if the function is call on an empty stack it indicates “Underflow”
// pop function
// return top most element in the stack
// and removes it from the stack
// Underflow if stack is empty
This method returns the topmost element of stack and removes it. Return underflow when called on an empty stack.
- Peek() : returns the top most elements in the stack, but doesn’t delete it.
// peek function
// return the top most element from the stack
// but does'nt delete it.
Return the topmost element without removing it from the stack.
This are the three basic operation perform by an Stack lets declare some helper method which can be useful while working with stack.
- isEmpty() : return true if the stack is empty
// isEmpty function
// return true if stack is empty
Returns true if the stack is empty.
- printStack() : This method returns a string in which all the element of an stack is concatenated.
// printStack function
var str =
(var i =
; i <
Note : Different helper function can be declared in Stack class as per the requirement. Now as we are done with defining the stack class lets use it.
In this example we would create an object of stack class and test few functions of it.
Some more functions of stack class
Once we are done with implementing and testing the stack class now we can use it in different application.
Application: Evaluation of Postfix Expression
In this example, we would use the above stack class to evaluate postfix expression
This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.