implementing stacks in c++ java using build in classes

                               Stack in C++ STL

The C++ STL offers a built-in class named stack for implementing the stack data structure easily and efficiently. This class provides almost all functions needed to perform the standard stack operations like push(), pop(), peek(), remove() etc..

Syntax:

stack< data_type > stack_name;

Here,
data_type: This defines the type of data to be
stored in the stack.
stack_name: This specifies the name of the stack.


Some Basic functions of Stack class in C++:

empty() – Returns whether the stack is empty.

size() – Returns the size of the stack.

top() – Returns a reference to the topmost element of the stack.

push(g) – Adds the element ‘g’ at the top of the stack.

pop() – Deletes the topmost element of the stack.

All of the above functions work in O(1) time complexity.


                                Stack class in Java

Java Collection framework provides a Stack class which models and implements the Stack data structure. The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search and peek. The class can also be said to extend Vector and treats the class as a stack with the five mentioned functions. The class can also be referred to as the subclass of Vector.

The class supports one default constructor Stack() which is used to create an empty stack.

Methods in Stack class:

Object push(Object element) : Pushes an element on the top of the stack.

Object pop() : Removes and returns the top element of the stack. An 'EmptyStackException' exception is thrown if we call pop() when the invoking stack is empty.

Object peek() : Returns the element on the top of the stack, but does not remove it.

boolean empty() : It returns true if nothing is on the top of the stack. Else, returns false.

int search(Object element) : It determines whether an object exists in the stack. If the element is found, it returns the position of the element from the top of the stack. Else, it returns -1.





No comments

darkmode