STACKS.!

@sherlocked
2 min readAug 16, 2020

--

Stack is a linear data structure that is used to store the collection of objects. It is based on Last-In-First-Out (LIFO).

The stack data structure has the two most important operations that are push and pop.Other operations include peek and empty.

Java collection framework provides many classes which also includes the Stack class that provides us the operations like pop,push,peek, search etc. etc..

Photo by Bekir Dönmez on Unsplash

if the top value in a stack is :-

N-1 : stack is full;

-1 :stack is empty;

N: stack is in overflow condition.

0:stack has only a single element.

But , before using the stack class , import the java.util package .Then create an object of the stack class.

The Stack class contains only the default constructor that creates an empty stack.

public Stack()

stack sk=new stack();

Methods of a Stack class:-

  1. empty(): check the stack is empty or not.If the stack is empty, it returns true, else returns false. eg:

public boolean empty().

2.push(): inserts an item onto the top of the stack.It passes a parameter item to be pushed into the stack. eg:

public E push(E item)

3. pop() Method

The method removes an object at the top of the stack and returns the same object. It throws EmptyStackException if the stack is empty.

public E pop()

4. Stack Class peek() Method

It looks at the element that is at the top in the stack. It also throws EmptyStackException if the stack is empty.

public E peek()

stacks data structure can be many applications and operations .The simplest is to use in the parenthesis questions.

one such example is to remove the outermost parenthisis.

program implementation to remove the outermost parenthesis is :

the input string is already passed in the function.

input: “(()())(())”

class Solution {
public:
string removeOuterParentheses(string S) {
string r = "", cur = "";
int depth = 0;
for (int i = 0; i < S.size(); ++ i) {
if (S[i] == '(') {
depth ++;
if (depth > 1) {
cur += "(";
}
} else {
depth --;
if (depth == 0) {
r += cur;
cur = "";
} else {
cur += ")";
}
}
}
return r;
}
};

To know better implementation of stack you can practise it on one of the online platforms.

--

--