Skip to content

Instantly share code, notes, and snippets.

@pavelnganpi
Last active August 29, 2015 14:04
Show Gist options
  • Save pavelnganpi/c60f614a7e9511784036 to your computer and use it in GitHub Desktop.
Save pavelnganpi/c60f614a7e9511784036 to your computer and use it in GitHub Desktop.
public class Stack {
int top;
int[] stackA;
int size;
public Stack(int size){
stackA = new int[size];
top = -1;
this.size=size;
}
public void push(int data){
if(top+1<this.size){
top++;
stackA[top]=data;
}
else{
System.out.println("stack is full");
}
}
public void pop(){
if(size()>0){
System.out.println(stackA[top]);
stackA[top] =-1;
top--;
}
else{
System.out.println("empty stack");
}
}
public int size(){
return top+1;
}
public void peek(){
System.out.println(stackA[top]);
}
public static void main(String []args){
Stack stack = new Stack(10);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(6);
stack.push(7);
stack.push(8);
stack.push(9);
stack.push(10);
stack.push(11);
System.out.println(stack.size());
stack.peek();
}
}
@satveersm
Copy link

what will be your approach if we need a dynamically growing stack.....

In place of fixed array can we use other ds....in c++ vector is a solution bcoz vector grow dynamic but lot of allocation deallocation so i prefer a singly linklist

insert method do insert at begining and top will be head

Insert 2 3 4 5 6 7
Top
|
7-->6--->5---->3----->2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment