Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package its101.mdwk07;
- //Create a custom Stack class for creating stack
- public class Stack {
- private final int maxSize;
- private final int[] stackArray;
- private int top;
- public Stack(int h) {
- maxSize = h;
- stackArray = new int[maxSize];
- top = -1;
- }
- //Create push() method, this will be use to push new element to the top of the stack
- public void push(int j) {
- if (top >= (maxSize - 1)){
- System.out.println("Error: Stack is overflow");
- }
- else {
- stackArray[++top] = j;
- System.out.println(j + " is pushed into the stack");
- }
- }
- //Create pop() method, this will be use to pop element from the top of the stack
- public int pop() {
- if (top < 0){
- System.out.print("Error: Stack is underflow");
- }
- else {
- int k = stackArray[top--];
- System.out.println(k + " is popped from the stack");
- }
- return 0;
- }
- //Create peek() method, this will look at the top element of the stack without removing it
- public int peek() {
- return stackArray[top];
- }
- //Create print() method, this will print the stack's elements
- void printStack(){
- for(int i = top;i>-1;i--){
- System.out.print(" "+ stackArray[i]);
- }
- System.out.println();
- }
- //Create isEmpty() method, this will check if the stack is empty or not
- public boolean isEmpty() {
- return (top == -1);
- }
- //Create isFull() method, this will check if the stack is full or the set maxSize s is reached
- public boolean isFull() {
- return (top == maxSize -1);
- }
- public static void main(String[] args) {
- // Create stack object
- Stack MyStack = new Stack(5); // maxSize is set to 5
- // Check if stack is empty using isEmpty()
- boolean emptyResult = MyStack.isEmpty();
- System.out.println("Is the stack empty? " + emptyResult); // It will print true because the stack is empty
- // Push elements into the stack
- MyStack.push(1);
- MyStack.push(2);
- MyStack.push(3);
- MyStack.push(4);
- MyStack.push(5);
- // Print the stack element using the print()
- System.out.print("The element of the stack: ");
- MyStack.printStack();
- // Check again if stack is empty using isEmpty()
- emptyResult = MyStack.isEmpty();
- System.out.println("Is the stack empty? " + emptyResult); // It will print false because the stack is now contain elements
- // Check if stack is full using isFull()
- boolean fullResult = MyStack.isFull();
- System.out.println("Is the stack full? " + fullResult); // It will print true because the maxSize is reached
- // Check what element at the top of the stack using peek()
- int topElement = MyStack.peek();
- System.out.println("Element at top of stack: " + topElement);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement