0% found this document useful (0 votes)
71 views13 pages

Stacks

The document discusses various implementations of stacks using arrays and linked lists in Java. It provides code to implement basic stack operations like push, pop, peek etc. using both arrays and linked lists. It also discusses various stack based problems and their solutions like finding the next greater element to the right/left, valid parentheses, minimum additions to make valid parentheses etc.

Uploaded by

Shyam Bambal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views13 pages

Stacks

The document discusses various implementations of stacks using arrays and linked lists in Java. It provides code to implement basic stack operations like push, pop, peek etc. using both arrays and linked lists. It also discusses various stack based problems and their solutions like finding the next greater element to the right/left, valid parentheses, minimum additions to make valid parentheses etc.

Uploaded by

Shyam Bambal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 13

Implementation of Stacks Using Arrays(Static method)

import java.util.*;
class Stack {
private int arr[];
private int top;

public Stack(int size)


{
arr = new int[size];
top = -1;
}

public boolean isEmpty()


{
return (top == -1);
}

public boolean isFull()


{
return (top == arr.length-1);
}

public void push(int ele)


{
if(isFull())
{
System.out.println("Stack is Full");
return;
}
arr[++top] = ele;
}

public int pop()


{
if(isEmpty())
{
System.out.println("Stack is Empty");
return -1;
}
int res = arr[top];
top--;
return res;
}

public int peak()


{
if(isEmpty())
{
System.out.println("Stack is Empty");
return -1;
}
return arr[top];
}

public int size()


{
return top+1;
}
}
public class Main
{
public static void main(String[] args) {
Stack st = new Stack(5);
st.push(1);
st.push(2);
st.push(3);
st.push(4);
st.push(5);
st.pop();
st.peak();
st.push(6);

System.out.println(st.size());
System.out.println(st.peak());
System.out.println(st.pop());
System.out.println(st.peak());
st.push(23);

while(!st.isEmpty()){
System.out.println(st.pop());
}
}
}
-----------------------------------------------------------------
//Implementation of Stack using LinkedList(Dynamic in Nature)

class Node {
public int data;
public Node next;

public Node(int data)


{
this.data = data;
this.next = null;
}
}

class LLStack
{
public Node head;
public int size;

public LLStack()
{
head = null;
size = 0;
}

public boolean isEmpty()


{
return head == null;
}

public void addFirst(int ele)


{
Node temp = new Node(ele);
temp.next = head;
head = temp;
}

public void push(int ele)


{
addFirst(ele);
size++;
}

public int pop()


{
if(isEmpty())
{
System.out.println("Stack is Empty");
return -1;
}
int res = head.data;
head = head.next;
size--;

return res;
}

public int peak()


{
if(isEmpty())
{
System.out.println("Stack is Empty");
return -1;
}
return head.data;
}

public int size()


{
return size;
}
}
public class Main
{
public static void main(String[] args) {
LLStack st = new LLStack();
st.push(1);
st.push(2);
st.push(3);
st.push(4);
st.push(5);
st.pop();
st.peak();
st.push(6);

while(!st.isEmpty()){
System.out.println(st.pop());
}
}
}
-----------------------------------------------------------------------
//Next Greater Element To The Right
public static int[] solve(int[] arr){
int[] nge = new int[arr.length];
Stack<Integer>st = new Stack<>();

st.push(arr[arr.length-1]);
nge[arr.length-1] = -1;

for(int i=arr.length-2; i>=0; i--){

while(st.size()>0 && arr[i]>=st.peek()){


st.pop();
}
if(st.size()==0){
nge[i] = -1;
}else{
nge[i] = st.peek();
}
st.push(arr[i]);
}
return nge;
}

5 3 8 -2 7
8 8 -1 7 -1
-----------------------------------------------------------------
//Next Greater Element To The Left

public static int[] solve(int[] arr) {


int nge[] = new int[arr.length];
Stack<Integer>st = new Stack<>();

for(int i=0; i<arr.length; i++){


while(st.size()>0 && arr[i]>=st.peek()){
st.pop();
}

if(st.size()==0){
nge[i] = -1;
}else{
nge[i] = st.peek();
}
st.push(arr[i]);
}
return nge;
}

--------------------------------------------------------
//Next Smaller Element To The Right

public static int[] solve(int[] arr) {


int n = arr.length;
int[] nse = new int[n];
Stack<Integer>st = new Stack<>();

for(int i=n-1; i>=0; i--){


while(st.size()>0 && st.peek()>=arr[i]){
st.pop();
}
if(st.size()==0){
nse[i]=-1;
}else{
nse[i]=st.peek();
}
st.push(arr[i]);
}
return nse;
}

Input: 5 3 8 -2 7
Output: 3 -2 -2 -1 -1
-----------------------------------------------------------
//Next Smaller Element To The Left

public static int[] solve(int[] arr) {


int n = arr.length;
int[] nse = new int[n];
Stack<Integer>st = new Stack<>();

for(int i=0; i<n; i++){


while(st.size()>0 && arr[i]<=st.peek()){
st.pop();
}
if(st.size()==0){
nse[i]=-1;
}else{
nse[i]=st.peek();
}
st.push(arr[i]);
}
return nse;
}

Input: 5 3 8 -2 7
Output: -1 -1 3 -1 -2
-----------------------------------------------------------------------
//Next Greater Element I

public static int[] nextGreaterElement(int[] nums, int[] query) {


int[] nge = nextGreaterRight(nums);
HashMap<Integer, Integer>map = new HashMap<>();

for(int i=0; i<nums.length; i++){


map.put(nums[i], nge[i]);
}

int[] ans = new int[query.length];


for(int i=0; i<query.length; i++){
ans[i] = map.get(query[i]);
}

return ans;
}

query : 4 1 2
arr : 1 3 4 2
nge : 3 4 -1 -1
ans: -1 4 -1
-----------------------------------------------------------------------
//Next Greater Element(circular nums)

public static int[] nextGreaterElementII(int[] nums) {


int n = nums.length;
Stack<Integer>st = new Stack<>();
for(int i=n-2; i>=0; i--){
while(st.size()>0 && nums[i]>=st.peek()){
st.pop();
}
st.push(nums[i]);
}

int[] ans = new int[n];


for(int i=n-1; i>=0; i--){
while(st.size()>0 && nums[i]>=st.peek()){
st.pop();
}

ans[i] = st.size()==0? -1: st.peek();


st.push(nums[i]);
}

return ans;
}

Input: 1 2 1
output: 2 -1 2
-------------------------------------------------------------------------
//Largest Area Histogram 2

public static int largestRectangleArea(int[] heights) {


int n = heights.length;
Stack<Integer>st = new Stack<>();
st.push(-1);
int maxArea = 0;

for(int i=0; i<=n; i++){


int val = i==heights.length?0:heights[i];

while(st.peek()!=-1 && val<=heights[st.peek()]){


int rm = i;
int h = heights[st.pop()];
int lm = st.peek();
maxArea = Math.max(maxArea, h*(rm-lm-1));
}
st.push(i);
}

return maxArea;
}

input: 2 1 5 6 2 3
output: 10
-----------------------------------------------------------------------
//Validate Stack Sequences

public static boolean validateStackSequences(int[] pushed, int[] popped) {


Stack<Integer>st = new Stack<>();
int j=0;
for(int e: pushed){
st.push(e);
while(st.size()>0 && st.peek()==popped[j]){
st.pop();
j++;
}
}
return j==popped.length;
}

pushed: 1 2 3 4 5
popped: 4 5 3 2 1
ans: true;
--------------------------------------------------------------------------------
//Minimum Add To Make Parentheses Valid

public static int minAddToMakeValid(String S) {


int o=0, k=0;
for(int i=0; i<S.length(); i++){
char ch = S.charAt(i);
if(ch=='('){
o++;
}else if(o!=0 && ch==')'){
o--;
}else if(o==0 && ch==')'){
k++;
}
}
return o+k;
}

//Stack

Stack<Character>st = new Stack<>();


for(int i=0; i<S.length(); i++){
char ch = S.charAt(i);
if(ch=='('){
st.push(ch);
}else{
if(st.size()>0 && st.peek()=='('){
st.pop();
}else{
st.push(ch);
}
}
}
return st.size();

input: ()))((
output: 4
------------------------------------------------------------------
//Remove Outermost Parentheses

public static String removeOuterParentheses(String s) {


Stack<Character>st = new Stack<>();
StringBuilder sb = new StringBuilder();
for(int i=0; i<s.length(); i++){
char ch = s.charAt(i);
if(ch=='('){
if(st.size()>0){
sb.append(ch);
}
st.push(ch);

}else{
st.pop();
if(st.size()>0){
sb.append(ch);
}

}
}
return sb.toString();
}

(()())(())
ans : ()()()
-----------------------------------------------------------------------
//Score Of Parentheses

public static int scoreOfParentheses(String s) {


Stack<Integer> st = new Stack<>();
for(int i=0; i<s.length(); i++){

if(s.charAt(i)=='('){
st.push(-1);
}else{
if(st.peek()==-1){
st.pop();
st.push(1);
}else{
int val = 0;
while(st.peek()!=-1){
val += st.pop();
}
st.pop();
st.push(2*val);
}
}
}
int val = 0;
while(st.size()>0){
val += st.pop();
}
return val;
}

(()(())) Score of ()()() string is 3 => 1 + 1 + 1


ans:6 Score of (()) string is 2 => 2 * 1

-----------------------------------------------------------
//

Stack< Character> st = new Stack< >();


for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == ')') {
if (st.peek() == '(') {
System.out.println(true);
return;
} else {
while (st.peek() != '(') {
st.pop();
}
st.pop();
}
} else {
st.push(ch);
}
}

System.out.println(false);
}

------------------------------------------------------------------------
//Balanced Brackets

Stack< Character> st = new Stack<>();

for (int i = 0; i < str.length(); i++)


{
char ch = str.charAt(i);
if (ch == '(' || ch == '[' || ch == '{')
{
st.push(ch);
}
else if (ch == ')')
{
boolean val = handleClosing(st, '(');
if (val == false)
{
System.out.println(val);
return;
}
}
else if (ch == ']')
{
boolean val = handleClosing(st, '[');
if (val == false)
{
System.out.println(val);
return;
}
}
else if (ch == '}')
{
boolean val = handleClosing(st, '{');
if (val == false)
{
System.out.println(val);
return;
}
}
else
{
}
}
if (st.size() == 0)
{
System.out.println(true);
}
else
{
System.out.println(false);
}

}
public static boolean handleClosing(Stack < Character> st, char corresopch)
{
if (st.size() == 0)
{
return false;
}
else if (st.peek() != corresopch)
{
return false;
}
else
{
st.pop();
return true;
}
}
-----------------------------------------------------------------------------------
----
//Remove K Digits

String num = read.readLine();


int k = Integer.parseInt(read.readLine());

Stack<Character>st = new Stack<>();

for(int i=0; i<num.length(); i++){


char ch = num.charAt(i);

while(st.size()>0 && k>0 && st.peek()>ch){


st.pop();
k--;
}
st.push(ch);
}

while(k>0){
st.pop();
k--;
}

char ans[] = new char[st.size()];


int h = ans.length-1;
while(h>=0) ans[h--] = st.pop();

int d = 0;
while(d<ans.length && ans[d] == '0') d++;

StringBuilder sb = new StringBuilder();


while(d < ans.length) sb.append(ans[d++]);
if(sb.length()==0) sb.append('0');
System.out.println(sb);
}

input: 1432219
k : 3
output: 1219
------------------------------------------------------------------------
//Asteroid Collision

public static int[] asteroidCollision(int[] asteroids) {


Stack<Integer> st = new Stack<>();

for(int val : asteroids){


if(val > 0){
st.push(val);
}else{
while(st.size() > 0 && st.peek() > 0 && st.peek() < -val){
st.pop();
}
if(st.size()>0 && st.peek() == -val){
st.pop();
}else if(st.size()>0 && st.peek() > -val){

}else{
st.push(val);
}
}
}

int[] ans = new int[st.size()];


int i = ans.length-1;
while(i>=0) ans[i--] = st.pop();

return ans;
}

input: 3 2 -1 3 -3 3
output: 1 -4
------------------------------------------------------------------------------
//Trapping Rain Water

public static int trap(int[] height) {


Stack<Integer>st = new Stack<>();

int ans = 0;
for(int i=0, n=height.length; i<n; i++){
while(st.size()>0 && height[st.peek()]<=height[i]){
int rm = i;
int curr = height[st.pop()];
if(st.size()==0) break;
int lm = st.peek();

int width = rm-lm-1;


ans += (Math.min(height[rm],height[lm])-curr)*width;
}
st.push(i);
}
return ans;
}
------------------------------------------------------------------------------
//Celebrity Problem

public static void findCelebrity(int[][] arr) {


Stack<Integer>st = new Stack<>();
for(int i=0; i<arr.length; i++){
st.push(i);
}

while(st.size()>=2){
int i = st.pop();
int j = st.pop();

if(arr[i][j]==1){
st.push(j);
}else{
st.push(i);
}
}

int pot = st.pop();


for(int i=0; i<arr.length; i++){
if(i!=pot){
if(arr[i][pot]==0 || arr[pot][i]==1){
System.out.println("none");
}
}
}
System.out.println(pot);
}

4
0000 //celeb is knows no one arr[i][j]=0 i may be celeb.
1011 //everyone knows celeb arr[i][j]=1 j may be celeb;
1101
1110
ans: 0
-----------------------------------------------------------------

You might also like