create a stack class based on an array of type double of fixed size. In the clas
ID: 3806730 • Letter: C
Question
create a stack class based on an array of type double of fixed size. In the class,
The array should have the default size of 5.
The array size should be settable via a constructor.
The following methods must be implemented:
push – inserts a value a the top of the stack
pop – returns the top value, removing it from the stack
isEmpty – returns true if the stack is empty, false otherwise
isFull - – returns true if the stack is full, false otherwise
Please notice you must use an array not an arraylist or any other list. Im having trouble with a couple parts of it. Thanks
Also use java
Explanation / Answer
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Stack {
private int top;
private int item[];
Stack(int size) {
top = -1;
item = new int[size];
}
public void IsFull(){
if(top==size-1)
System.out.println("full");
else
System.out.println("not full");
}
public void IsEmpty(){
if(top==-1)
System.out.println("Empty");
else
System.out.println("not Empty");
}
void push(int data) {
if (top == item.length - 1) {
System.out.println("Stack is Full");
} else {
item[++top] = data;
System.out.println("Pushed :" + item[top]);
}
}
int pop() {
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
} else {
System.out.println("Pop : " + item[top]);
return item[top--];
}
}
}
class StackExample {
public static void main(String[] args) throws IOException {
Stack stk = new Stack(5);
boolean yes=true;
stk.push(10);/* Inserting element in the stack at index 0*/
stk.push(1);/* Inserting element in the stack at index 1*/
stk.IsFull();/* checking whether Stack is full or not using index updated*/
stk.pop(1);/*Removing the top element of the stack at index 1*/
stk.pop(10);/*Removing the top element of the stack at index 0*/
stk.IsEmpty();/* checking whether Stack is empty or not using current index*/
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.