Welcome Message

Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.

January 23, 2018

Stack of Integers

package com.mylearnings;

public class IntStack {

int size;
int[] stack;
int top;

IntStack() {
size = 50;
top = -1;
stack = new int[50];
}

IntStack(int size) {
this.size = size;
top = -1;
stack = new int[size];
}

public boolean push(int value) {

if (!isFull()) {
stack[++top] = value;
return true;
}
return false;
}

public int pop() {
return stack[top--];
}

public boolean isFull() {
return top == size - 1;
}

public boolean isEmpty() {
return top == -1;
}

}

----------------------------------------------------------------

Main class

package com.mylearnings;

public class IntStackMain {

public static void main(String[] args) {
IntStack stack = new IntStack(10);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());

}

}

No comments: