[go: up one dir, main page]

0% found this document useful (0 votes)
2 views1 page

Stack

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)
2 views1 page

Stack

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/ 1

class Stack{

int size,top=-1;
int [] array;
public Stack(int size){
this.size=size;
array = new int[size];
}
void push(int ele){
if(top>size){
System.out.println("Array is over flow.");
}
else{
top++;
array[top]=ele;
}
}
public int pop(){
if(top<0){
System.out.println("Array is underflow");
return -1;
}
else{
return array[top--];

}
}
int peek(){
return array[top];
}
boolean isEmpty(){
return(top == -1);
}
String display(){
String print = "[";
for(int i=0;i<size;i++){
print+=array[i]+" ";
}
print+="]";
return print;
}
}
class Main{
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(4);
stack.push(2);
stack.push(3);
stack.push(1);
stack.push(16);
System.out.println("Size of stack: "+stack.size);
System.out.println("Top element: "+stack.peek());
System.out.println("Pop element: "+stack.pop());
System.out.println("Is stack empty: "+stack.isEmpty());
System.out.println("Array: "+stack.display());
}
}

You might also like